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
Add a comment  | 

6 Answers 6

Reset to default 21

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

本文标签: Boolean algebra in javascriptStack Overflow