在JavaScript中,python any()和all()函数的等效是什么?

时间:2022-02-06 23:07:22

Python does has built in functions any() and all(), which are applied on a list(array in JavaScript) as following-

Python确实内置了函数any()和all(),它们应用于列表(JavaScript中的数组),如下所示

any(): Return True if any element of the iterable is true. If the iterable is empty, return False.
all(): Return True if all elements of the iterable are true (or if the iterable is empty).

We can create our customized functions for above, but please let me know if there any equivalent built-in functions available in JavaScript.

我们可以为上面创建我们的定制函数,但是请让我知道JavaScript中是否有相应的内置函数。

1 个解决方案

#1


18  

The Python documentation gives you pure-python equivalents for both functions; they are trivial to translate to JavaScript:

Python文档提供了两个函数的纯Python对等物;翻译成JavaScript很简单:

function any(iterable) {
    for (var index = 0; index < iterable.length; ++index) {
        if (iterable[index]) return true;
    }
    return false;
}

and

function all(iterable) {
    for (var index = 0; index < iterable.length; ++index) {
        if (!iterable[index]) return false;
    }
    return true;
}

Recent browser versions (implementing ECMAScript 5.1, Firefox 1.5 and IE 9) have native support in the form of Array.some and Array.every; these take a callback that determines if something is 'true' or not:

最近的浏览器版本(实现了ECMAScript 5.1、Firefox 1.5和IE 9)以数组的形式提供了本地支持。一些和Array.every;这些都是一个回调,它决定了什么东西是“真实”的:

some_array.some(function(elem) { return !!elem; });
some_array.every(function(elem) { return !!elem; });

The Mozilla documentation I linked to has polyfills included to recreate these two methods in other JS implementations.

我链接到的Mozilla文档包含了在其他JS实现中重新创建这两个方法的polyfill。

#1


18  

The Python documentation gives you pure-python equivalents for both functions; they are trivial to translate to JavaScript:

Python文档提供了两个函数的纯Python对等物;翻译成JavaScript很简单:

function any(iterable) {
    for (var index = 0; index < iterable.length; ++index) {
        if (iterable[index]) return true;
    }
    return false;
}

and

function all(iterable) {
    for (var index = 0; index < iterable.length; ++index) {
        if (!iterable[index]) return false;
    }
    return true;
}

Recent browser versions (implementing ECMAScript 5.1, Firefox 1.5 and IE 9) have native support in the form of Array.some and Array.every; these take a callback that determines if something is 'true' or not:

最近的浏览器版本(实现了ECMAScript 5.1、Firefox 1.5和IE 9)以数组的形式提供了本地支持。一些和Array.every;这些都是一个回调,它决定了什么东西是“真实”的:

some_array.some(function(elem) { return !!elem; });
some_array.every(function(elem) { return !!elem; });

The Mozilla documentation I linked to has polyfills included to recreate these two methods in other JS implementations.

我链接到的Mozilla文档包含了在其他JS实现中重新创建这两个方法的polyfill。