admin管理员组文章数量:1410674
I have an instance where arrays of potentially different length can look like this...
Array [ true, false, false, true ]
Or
Array [ true, true, true, false, true ]
Or
Array [ true, true, true ]
I need to iterate through an array and ONLY trigger a new event if there is ONE instance of "false".
Out of sample arrays I presented,, this one wold be the only one that is valid
Array [ true, true, true, false, true ]
What would be the least elaborate way to acplish this?
I have an instance where arrays of potentially different length can look like this...
Array [ true, false, false, true ]
Or
Array [ true, true, true, false, true ]
Or
Array [ true, true, true ]
I need to iterate through an array and ONLY trigger a new event if there is ONE instance of "false".
Out of sample arrays I presented,, this one wold be the only one that is valid
Array [ true, true, true, false, true ]
What would be the least elaborate way to acplish this?
Share Improve this question asked Dec 11, 2014 at 5:02 GRowingGRowing 4,72713 gold badges55 silver badges75 bronze badges2 Answers
Reset to default 7You could do it by using Array.filter
var arr = [ true, true, true, false, true ];
if(arr.filter(function(b){ return !b; }).length == 1){
// trigger the event
}
The above filters to just contain Array
of false
and then we check if the length
of that Array
is 1
Another creative way of doing this might be using replace
and indexOf
, where you're just replacing the first occurrence of false
in a String
formed by joining the arr
and checking if there are still any false
in the string and negate it with !
operator to achieve the results.
if(!(arr.join("").replace("false","").indexOf("false") > -1)){
// trigger
}
Amit Joki already has a working answer, but I'd just like to share another solution using reduce
:
var count = arr.reduce(function(prevVal, currVal) {
return prevVal + (!currVal ? 1 : 0);
}, 0);
if (count === 1) {
// Do something
}
本文标签: JQuery or JavaScriptCount how many array elements are truefalseStack Overflow
版权声明:本文标题:JQuery or JavaScript - Count how many array elements are truefalse - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744942793a2633592.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论