every()與some()方法都是JS中數組的迭代方法。
every()是對數組中每一項運行給定函數,如果該函數對每一項返回true,則返回true。
some()是對數組中每一項運行給定函數,如果該函數對任一項返回true,則返回true。
function isBigEnough(element, index, array) {
return (element >= 10);
}
passed = [12, 5, 8, 130, 44].every(isBigEnough);
//false
passed = [12, 54, 18, 130, 44].every(isBigEnough);
// true
passed = [2, 5, 8, 1, 4].some(isBigEnough);
// false
passed = [12, 5, 8, 1, 4].some(isBigEnough);
// true
在第 5 版時,every 被添加進 ECMA-262 標准;因此在某些實現環境中不被支持。你可以把下面的代碼放到腳本的開頭來解決此問題,該代碼允許
在那些沒有原生支持 every 的實現環境中使用它。該算法是 ECMA-262 第5版中指定的算法,假定 Object 和 TypeError 擁有它們的初始值,
且 fun.call 等價於Function.prototype.call。
if (!Array.prototype.every)
{
Array.prototype.every = function(fun /*, thisArg */)
{
'use strict';
if (this === void 0 || this === null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== 'function')
throw new TypeError();
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++)
{
if (i in t && !fun.call(thisArg, t[i], i, t))
return false;
}
return true;
};
}
Array.prototype.some()
在第 5 版時,some 被添加進 ECMA-262 標准;這樣導致某些實現環境可能不支持它。你可以把下面的代碼插入到腳本的開頭來解決此問題,
從而允許在那些沒有原生支持它的實現環境中使用它。該算法是 ECMA-262 第 5 版中指定的算法,假定 Object 和 TypeError 擁有他們的初始值,
且 fun.call 等價於 Function.prototype.call。
if (!Array.prototype.some)
{
Array.prototype.some = function(fun /*, thisArg */)
{
'use strict';
if (this === void 0 || this === null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== 'function')
throw new TypeError();
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++)
{
if (i in t && fun.call(thisArg, t[i], i, t))
return true;
}
return false;
};
}
總結:
方法區別
every() 每一項都返回true才返回true
some() 只要有一項返回true就返回true
類似&&和||的關系
本文整理自:https://www.cnblogs.com/leejersey/p/5483247.html
本文整理自:http://www.cnblogs.com/yourstars/p/7822858.html