Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent to Python's all function in JavaScript or jQuery?

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?

like image 244
Khaelex Avatar asked Apr 30 '14 14:04

Khaelex


People also ask

What is the equivalent of on in jQuery to JavaScript?

In jQuery, you can listen to events for dynamically added elements using the on() function. The equivalent in JavaScript is addEventListener() function.

Can you use jQuery in Python?

pyquery: a jquery-like library for pythonpyquery allows you to make jquery queries on xml documents. The API is as much as possible the similar to jquery. pyquery uses lxml for fast xml and html manipulation. This is not (or at least not yet) a library to produce or interact with javascript code.

Is there a zip function in JavaScript?

js | zip() Function. The zip() function is used to combine the values of given array with the values of original collection at a given index. In JavaScript, the array is first converted to a collection and then the function is applied to the collection.


1 Answers

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
like image 127
Cerbrus Avatar answered Oct 03 '22 20:10

Cerbrus