0

如何检查“playerChoices”中的数组是否等于“test1”数组中的索引 0。这是我现在的代码。我错过了什么?提前致谢。

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');
    };
4

1 回答 1

4

当你在循环内返回时,如果第一项不符合要求false,它总是会返回。false

您可以使用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]))

于 2020-10-14T13:57:03.930 回答