javascript中的布尔代数

Ale*_*lex 4 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]//this on the other hand should return false
Run Code Online (Sandbox Code Playgroud)

Lou*_*ens 19

我认为一个简单的解决方案就是

return array.indexOf(false) == -1
Run Code Online (Sandbox Code Playgroud)

  • 除非您手动定义indexOf函数,否则这将无法在ie7或更低版​​本中运行 (2认同)

dig*_*ath 15

试试Array.reduce:

[false,true,true,true].reduce(function(a,b) { return a && b; })  // false

[true,true,true,true].reduce(function(a,b) { return a && b; }) // true
Run Code Online (Sandbox Code Playgroud)


Dav*_*ver 5

你的意思是:

function all(array) {
    for (var i = 0; i < array.length; i += 1)
        if (!array[i])
            return false;
    return true;
}
Run Code Online (Sandbox Code Playgroud)

或者你正在寻找更复杂的东西?