every() 方法會測試陣列中的所有元素是否都能通過所提供的測試函式,只要有一個不符合就回傳 false,全部符合才回傳 true。它曾是 JavaScript 對 ECMA-262 標準的擴充,因此本文也附上相容舊環境的 polyfill。
array.every(callback[, thisObject]);
參數說明:
・callback:用來測試每個元素的函式。
・thisObject:執行 callback 時作為 this 使用的物件。
若陣列中每個元素都滿足測試函式,則回傳 true。
if (!Array.prototype.every){
Array.prototype.every = function(fun /*, thisp*/){
var len = this.length;
if (typeof fun != "function") throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++){
if (i in this && !fun.call(thisp, this[i], i, this))
return false;
}
return true;
};
}
function isBigEnough(element, index, array){
return (element >= 10);
}
var passed = [12, 5, 8, 130, 44].every(isBigEnough);
document.write("First Test Value : " + passed); // false(5、8 小於 10)
passed = [12, 54, 18, 130, 44].every(isBigEnough);
document.write("Second Test Value : " + passed); // true
執行後會輸出:
First Test Value : falseSecond Test Value : true
every() 適合用於「驗證整批資料是否都合乎規範」的場景,例如表單中每個欄位是否都已填寫。與它相對的 some() 則是「只要有一個符合即為 true」,可依邏輯需求靈活選用。