我有一个数组,其属性为 id
和 value
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/