JavaScript中的python any()和all()函数的等价物是什么? [英] What is the equivalent of python any() and all() functions in JavaScript?
问题描述
Python确实内置了函数 any()和 all(),这些函数应用于列表(JavaScript中的数组),如下所示 -
Python does has built in functions any() and all(), which are applied on a list(array in JavaScript) as following-
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).
我们可以为上面创建我们的定制功能,但是如果有任何等效的内置功能请告诉我JavaScript中提供的函数。
We can create our customized functions for above, but please let me know if there any equivalent built-in functions available in JavaScript.
推荐答案
Python文档为你提供了两个函数的纯python等价物;它们很容易翻译成JavaScript:
The Python documentation gives you pure-python equivalents for both functions; they are trivial to translate to JavaScript:
function any(iterable) {
for (var index = 0; index < iterable.length; index++) {
if (iterable[index]) return true;
}
return false;
}
和
function all(iterable) {
for (var index = 0; index < iterable.length; index++) {
if (!iterable[index]) return false;
}
return true;
}
最近的浏览器版本(实施ECMAScript 5.1,Firefox 1.5 +,Chrome,Edge 12 +和IE 9)以的形式提供原生支持 Array.some
和 Array.every
;这些采取回调来确定某些事物是否为真:
Recent browser versions (implementing ECMAScript 5.1, Firefox 1.5+, Chrome, Edge 12+ 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:
some_array.some(function(elem) { return !!elem; });
some_array.every(function(elem) { return !!elem; });
我链接到的Mozilla文档包含了polyfill,用于在其他JS实现中重新创建这两个方法。
The Mozilla documentation I linked to has polyfills included to recreate these two methods in other JS implementations.
这篇关于JavaScript中的python any()和all()函数的等价物是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!