javascript中的布尔代数
有没有办法在JS中使用布尔代数 例如,我想循环一个包含true和false的数组,并将其简化为仅为true或false 使用布尔代数似乎是一种优雅的方法javascript中的布尔代数,javascript,boolean-logic,Javascript,Boolean Logic,有没有办法在JS中使用布尔代数 例如,我想循环一个包含true和false的数组,并将其简化为仅为true或false 使用布尔代数似乎是一种优雅的方法 [true,true,true,true] //would like to do a comparison that lets me //simply add the previous value to the current iteration of a loop // and have this return true [false
[true,true,true,true] //would like to do a comparison that lets me
//simply add the previous value to the current iteration of a loop
// and have this return true
[false,true,true,true]//this on the other hand should return false
你是说:
function all(array) {
for (var i = 0; i < array.length; i += 1)
if (!array[i])
return false;
return true;
}
函数全部(数组){
对于(变量i=0;i
或者你在寻找更复杂的东西吗?for(var i=0;ifor(var i=0; i < array.length;++i) {
if(array[i] == false)
return false;
}
return true;
if(数组[i]==false)
返回false;
}
返回true;
我认为一个简单的解决方案是
return array.indexOf(false) == -1
尝试
数组。减少:
[false,true,true,true].reduce(function(a,b) { return a && b; }) // false
[true,true,true,true].reduce(function(a,b) { return a && b; }) // true
你的意思是将它们全部“和”在一起吗?这在ie7或更低版本中不起作用,除非你手动定义indexOf函数+1,因为它很简单,可以很容易地转换为处理逻辑or而不是and的要求,并且它本质上与使用.indexOf()
的公认答案相同,只是它可以在所有浏览器中工作。
function boolAlg(bools) {
return !bools[0] ? false :
!bools.length ? true : boolAlg(bools.slice(1));
}
[false,true,true,true].reduce(function(a,b) { return a && b; }) // false
[true,true,true,true].reduce(function(a,b) { return a && b; }) // true