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

标签 javascript arrays angularjs arraylist

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

相关文章:

javascript - 我的 Json 数组只返回最后一个数组。如何解决?

javascript - 使用工厂登录 Angularjs FB

javascript - 发布 ASP.NET 网站

c++ - C++中的不同数字

javascript - 在React.js的父组件中使用react-router时,如何使用react context API将数据从父组件传递到子组件?

arrays - 将数组元素转换为其基类类型

angularjs - 具有不同动态内容的小部件(Angular-Gridster)

javascript - 如何使 href 与 ng-click 中的函数结果一起使用?

javascript - 单击时 jQuery 下拉列表不显示

javascript - 某些 OGG 文件无法在 Firefox 上播放