JQuery或JavaScript - 计算有多少数组元素为true / false

时间:2014-12-11 05:02:39

标签: javascript jquery arrays

我有一个实例,其中可能长度不同的数组看起来像这样......

Array [ true, false, false, true ]

或者

Array [ true, true, true, false, true ]

或者

Array [ true, true, true ]

如果有一个" false"的实例,我需要迭代一个数组并且只触发一个新事件。

我提出的样本数组中,这一个是唯一有效的数组

Array [ true, true, true, false, true ]

实现这一目标的最不精确的方法是什么?

2 个答案:

答案 0 :(得分:6)

您可以使用Array.filter

来完成
var arr = [ true, true, true, false, true ];
if(arr.filter(function(b){ return !b; }).length == 1){
   // trigger the event
}

以上过滤条仅包含Array false,然后我们会检查length的{​​{1}}是否为Array

另一种创造性的方式可能是使用1replace,您只需要替换indexOf中第一次出现的false String并检查字符串中是否还有arr,并使用false运算符取消它以获得结果。

!

答案 1 :(得分:4)

Amit Joki已经有working answer,但我想使用reduce分享另一个解决方案:

var count = arr.reduce(function(prevVal, currVal) {
    return prevVal + (!currVal ? 1 : 0);
}, 0);

if (count === 1) {
    // Do something
}