萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript Array.prototype.forEach() 完整指南:陣列迭代基石

前言

forEach() 方法對陣列每個元素執行一次指定的回呼函式。不同於 map(),它不回傳新陣列,主要用於副作用操作(如 DOM 更新、日誌記錄、資料發送)。

語法

array.forEach(callback(element[, index[, array]])[, thisArg])

參數說明

  • callback:每個元素執行的函式,參數同 every()。
  • thisArg(可選):callback 的 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>

重要特性

  • 不會改變原陣列(但 callback 可透過 array[index] 修改)。
  • 無法中途 break 或 continue,需改用 for...of 或 some()/every()。
  • 稀疏陣列會跳過空位(in 檢查)。

Polyfill

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。

copyright © 萬盛學電腦網 all rights reserved