开发者

Boolean algebra in javascript

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 i开发者_开发知识库teration of a loop

[true, true, true, true] // return true

[false, true, true, true] // return false


I 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));

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜