[英]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.