简体   繁体   English

如何检查两位数组是否与对象数组的某个部分相同?

[英]How to check if a two digit array is identical to a certain section of an object array?

How do I check if the array in 'playerChoices' equals, let's say, index 0 in 'test1' array.如何检查“playerChoices”中的数组是否等于“test1”数组中的索引 0。 This is my code as of now.这是我目前的代码。 What am I missing?我错过了什么? Thanks in advance.提前致谢。

var playerChoices = [1, 3];
const test1 = [{right: 1, wrong: 3}, {right: 2, wrong: 1}, {right: 3, wrong: 2}];

  function check() {
       for (var i = 0; i < test1.length; i++) {
          if (test1[i] !== playerChoices[i]) return false;
    }
      return true;
    };

  if(check()){
       console.log('true');
    };

When you return false inside the loop, it will always return false if the first item does not meet the requirements.当您返回false的循环中,它总是返回false ,如果第一项不符合要求。

You can use Array.some() to check if any of them is equal as followings:您可以使用Array.some()来检查它们中的任何一个是否相等,如下所示:

 const test1 = [{right:1,wrong:3},{right:2,wrong:1},{right:3,wrong:2}]; function check(playerChoices) { // You can use destructuring here to have a more readable code [playerRight, playerWrong] = playerChoices return test1.some(choice => choice.right === playerRight && choice.wrong === playerWrong) }; console.log(check([1, 3])) console.log(check([1, 4]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何检查新创建的 object 是否与阵列内的 object 相同 - How to check if a newly created object is identical to an object inside of an array 如何检查某个对象是否是JavaScript数组中的唯一对象? - How to check if a certain object is the only object in a JavaScript array? 在推送新的 object 之前检查阵列是否相同 object - Check array for identical object before pushing new object 如何检查 object 是否不是数组? - How to check if an object is not an array? 如何在 javascript 的 object 数组中获得相同的 object - How to get identical object within array of object in javascript 如何检查数组中的元素在javascript中是否相同(超过2个元素) - How to check if the elements of an array are identical in javascript (more than 2 elements) 如何根据两个属性对 object 的数组进行排序并检查愤怒是顺序的? - How to sort a array of object based on two properties and check the rage is sequential? 如何在 JavaScript 中合并两个不同的 object 数组? 检查以下示例 - How to merge two different array of object in JavaScript? Check below example 如何检查两个数组中的属性值 object 值 javascript - how to check property value in two array of object values javascript Javascript:如何检查数组中的某些项目 - Javascript: How to check for certain items in an array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM