在Python中,all()函数测试列表中的所有值是否为真.例如,我可以写
if all(x < 5 for x in [1, 2, 3, 4]):
print("This always happens")
else:
print("This never happens")
Run Code Online (Sandbox Code Playgroud)
在JavaScript或jQuery中是否有等效的功能?
Cer*_*rus 10
显然,确实存在:Array.prototype.every.来自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
Run Code Online (Sandbox Code Playgroud)
这意味着您不必手动编写它.但是,此功能在IE8上不起作用.
但是,如果您想要一个也适用于IE8的功能,您可以使用手动实现, 或者在mdn页面上显示的polyfill.
手册:
function all(array, condition){
for(var i = 0; i < array.length; i++){
if(!condition(array[i])){
return false;
}
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
用法:
all([1, 2, 3, 4], function(e){return e < 3}) // false
all([1, 2, 3, 4], function(e){return e > 0}) // true
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
705 次 |
| 最近记录: |