forEach() 方法對陣列每個元素執行一次指定的回呼函式。不同於 map(),它不回傳新陣列,主要用於副作用操作(如 DOM 更新、日誌記錄、資料發送)。
array.forEach(callback(element[, index[, array]])[, thisArg])
every()。this 綁定值。undefined。若需產生新陣列請使用 map()。
<script>
const arr = [12, 5, 8, 130, 44];
arr.forEach((value, index) => {
console.log(`[${index}] is ${value}`);
});
// 輸出:
// [0] is 12
// [1] is 5
// [2] is 8
// [3] is 130
// [4] is 44
</script>
array[index] 修改)。break 或 continue,需改用 for...of 或 some()/every()。in 檢查)。if (!Array.prototype.forEach) {
Array.prototype.forEach = 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);
}
};
}
forEach() 是陣列遍歷的標準工具,語意清晰且支援 thisArg 綁定。需中斷迴圈時請選擇 for...of。