every() 方法測試陣列中所有元素是否通過指定的測試函式。若全部通過回傳 true,否則回傳 false。此為 ES5 標準方法,現代瀏覽器皆原生支援。
array.every(callback(element[, index[, array]])[, thisArg])
element(目前元素)、index(索引)、array(原陣列)。需回傳布林值。this 值。布林值:所有元素通過測試為 true,否則 false。空陣列永遠回傳 true。
<script>
const isBigEnough = (element) => element >= 10;
console.log([12, 5, 8, 130, 44].every(isBigEnough)); // false
console.log([12, 54, 18, 130, 44].every(isBigEnough)); // true
// 空陣列
console.log([].every(() => false)); // true
</script>
if (!Array.prototype.every) {
Array.prototype.every = function(callback, thisArg) {
if (this == null) throw new TypeError('this is null or not defined');
const O = Object(this);
const len = O.length >>> 0;
if (typeof callback !== 'function') throw new TypeError(callback + ' is not a function');
for (let i = 0; i < len; i++) {
if (i in O && !callback.call(thisArg, O[i], i, O)) return false;
}
return true;
};
}
every() 是函數式程式設計的核心工具,搭配箭頭函式可撰寫極簡潔的驗證邏輯。記得處理空陣列邊界情況。