Is there a Python function equivalent for all functions in JavaScript or jQuery?

In Python, functions all()check to see 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?

+4
source share
1 answer

Apparently, it exists: 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 that you do not have to write it manually. However, this function does not work on IE8-.

However, if you want to use a function that also works for IE8, you can use the manual implementation, Or the polyfill shown on the mdn page .

Guide:

function all(array, condition){
    for(var i = 0; i < array.length; i++){
        if(!condition(array[i])){
            return false;
        }
    }
    return true;
}

Using:

all([1, 2, 3, 4], function(e){return e < 3}) // false
all([1, 2, 3, 4], function(e){return e > 0}) // true
+9
source

Source: https://habr.com/ru/post/1538749/


All Articles