[英]How to check if a newly created object is identical to an object inside of an array
[英]How to check if a two digit array is identical to a certain section of an object array?
如何检查“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');
};
当您返回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]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.