admin管理员组文章数量:1178539
Is there any way to use boolean algebra in JS?
Eg I would like to loop through an array containing true & false, and simplify it down to either only true, or false.
Doing it with boolean algebra seems like an elegant way to do it...
would like to do a comparison that lets me simply add the previous value to the current iteration of a loop
[true, true, true, true] // return true
[false, true, true, true] // return false
Is there any way to use boolean algebra in JS?
Eg I would like to loop through an array containing true & false, and simplify it down to either only true, or false.
Doing it with boolean algebra seems like an elegant way to do it...
would like to do a comparison that lets me simply add the previous value to the current iteration of a loop
[true, true, true, true] // return true
[false, true, true, true] // return false
Share
Improve this question
edited Dec 14, 2022 at 17:36
Lomefin
1,25214 silver badges45 bronze badges
asked Jul 14, 2011 at 18:03
AlexAlex
5,7247 gold badges44 silver badges65 bronze badges
1
- Do you mean 'and-ing' them all together? – n8wrl Commented Jul 14, 2011 at 18:04
6 Answers
Reset to default 21I think a simple solution would be
return array.indexOf(false) == -1
Try Array.reduce
:
[false,true,true,true].reduce((a,b) => a && b) // false
[true,true,true,true].reduce((a,b) => a && b) // true
You mean like:
function all(array) {
for (var i = 0; i < array.length; i += 1)
if (!array[i])
return false;
return true;
}
Or is there something more complex you're looking for?
function boolAlg(bools) {
var result = true;
for (var i = 0, len = bools.length; i < len; i++) {
result = result && bools[i]
}
return result;
}
Or you could use this form, which is faster:
function boolAlg(bools) {
return !bools[0] ? false :
!bools.length ? true : boolAlg(bools.slice(1));
}
for(var i=0; i < array.length;++i) {
if(array[i] == false)
return false;
}
return true;
ES6 Array.prototype.every
:
console.log([true, true, true, true].every(Boolean));
console.log([false, true, true, true].every(Boolean));
本文标签: Boolean algebra in javascriptStack Overflow
版权声明:本文标题:Boolean algebra in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1737997675a2046689.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论