Reputation: 762
In Python the all()
functions tests if all values in a list are true. For example, I can write
if all(x < 5 for x in [1, 2, 3, 4]):
print("This always happens")
else:
print("This never happens")
Is there an equivalent function in JavaScript or jQuery?
Upvotes: 5
Views: 1019
Reputation: 72947
Apparently, it does exist: Array.prototype.every
.
Example from mdn:
function isBigEnough(element, index, array) {
return (element >= 10);
}
var passed = [12, 5, 8, 130, 44].every(isBigEnough);
// passed is false
passed = [12, 54, 18, 130, 44].every(isBigEnough);
// passed is true
This means you won't have to write it manually. This function doesn't work on IE8-, though.
However, if you want a function that also works for IE8-, you can use a manual implementation, Or the polyfill shown on the mdn page.
Manual:
function all(array, condition){
for(var i = 0; i < array.length; i++){
if(!condition(array[i])){
return false;
}
}
return true;
}
Usage:
all([1, 2, 3, 4], function(e){return e < 3}) // false
all([1, 2, 3, 4], function(e){return e > 0}) // true
Upvotes: 10