gpt4 book ai didi

javascript - 使用javascript获取数组中真/假值的数量

转载 作者:行者123 更新时间:2023-11-30 07:00:25 25 4
gpt4 key购买 nike

我有一个数组,其属性为 idvalue

 var arrayObj=  [
{"id": 1, "value": true},
{"id": 2, "value": false},
{"id": 3, "value": true}
]

我需要获取具有属性 true/false 的对象的数量。我正在使用 Array.prototype.every() 但我的逻辑并没有像看起来那样按预期工作。谁能告诉我我在这里做错了什么?我没有显示计数

function checkIfFalse(value, index, ar) {
document.write(value + " ");
if (value === false)
return true;
else
return false;
}

if (arrayObj.every(checkIfFalse)) {
console.log("all are false");
}else {
console.log("all are true");
}

最佳答案

为什么不使用 .filter

// Your array object
var arrayObj = [
{"id": 1, "value": true},
{"id": 2, "value": false},
{"id": 3, "value": true}
];

// Count true items
var count = arrayObj.filter(function(s) { return s.value; }).length;

// Result
console.log("#True: " + count);

关于javascript - 使用javascript获取数组中真/假值的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32110128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com