forEach() 方法會對陣列中的每個元素依序執行指定的函式,是遍歷陣列最直觀的方式之一。它曾是 JavaScript 對 ECMA-262 標準的擴充,因此本文也附上相容舊環境的 polyfill。
array.forEach(callback[, thisObject]);
參數說明:
・callback:對陣列每個元素執行的函式。
・thisObject:執行 callback 時作為 this 使用的物件。
forEach() 本身沒有回傳值。
if (!Array.prototype.forEach){
Array.prototype.forEach = 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);
}
};
}
function printBr(element, index, array){
document.write("<br />[" + index + "] is " + element);
}
[12, 5, 8, 130, 44].forEach(printBr);
執行後會輸出:
[0] is 12
[1] is 5
[2] is 8
[3] is 130
[4] is 44
callback 函式會收到「目前元素、索引、整個陣列」三個參數,讓你能靈活處理每個位置。要特別注意的是,forEach() 不能用 break 提前中斷迴圈(可改用 some()、every() 或 for...of);此外它不會遍歷空位(sparse array 中的空缺)。理解這些特性,才能在不同情境下選用最合適的遍歷方式。