JavaScript: Array.prototype.every
arrayX.every(f)
-
Return
true
if the function f returntrue
for every element. As soon as f returnfalse
, exit the iteration and returnfalse
. If array is empty, returntrue
.
arrayX can be Array-Like Object.
The function f is passed 3 args: • current_element • current_index • arrayX. arrayX.every(f, thisArg)
- Use thisArg for this Binding of f
Use “every” as Boolean “AND” Connector
Array.prototype.every
can be used as a function version of the boolean operator “and” &&
.
For example, you have
[a,b,c,d]
and you want
f(a) && f(b) && f(c) && f(d)
.
// example of Array.prototype.every const f = (x => (x > 10)) ; // check if every item is greater than 10 console.log( [30 , 40, 50].every(f) ); // true console.log( [30 , 2, 50].every(f) ); // false
Use “every” as Loop with Break
“every” is useful as a forEach with break.
Here's example. Apply f to each element in order. Exit the loop when f returns false
.
// Array.prototype.every as loop, exit loop when a item is false const f = (x => { if ( x <= 3 ) { console.log( x ); return true; } else { return false; } }); [1,2,3,4,5,6].every(f); // prints // 1 // 2 // 3
[see Array.prototype.forEach]
「every」 on Empty Array
every
on empty array returns true
.
console.log( [].every(() => false) ); // true