陣列遍歷是日常開發最高頻操作。ES6+ 提供多種語法,各有適用場景與效能特性。本文系統對比 7 種主流方式,助你選對工具。
| 方法 | 語法 | 可中斷 | 回傳值 | 適用場景 | 效能 |
|---|---|---|---|---|---|
| for (C-style) | for(let i=0;i | ✅ break/continue | 無 | 需索引、高效能、複雜邏輯 | ⭐⭐⭐⭐⭐ |
| while | let i=0; while(i | ✅ | 無 | 同 for,條件複雜時 | ⭐⭐⭐⭐⭐ |
| for...of | for(const v of arr) | ✅ | 無 | 只需值、可迭代物件通用 | ⭐⭐⭐⭐ |
| forEach | arr.forEach((v,i,a)=>{}) | ❌ (需 throw) | undefined | 單純副作用(副作用:log、DOM 操作) | ⭐⭐⭐ |
| map | arr.map(v => ...) | ❌ | 新陣列 | 一對一轉換、鏈式操作 | ⭐⭐⭐ |
| filter | arr.filter(v => ...) | ❌ | 新陣列 | 篩選子集 | ⭐⭐⭐ |
| reduce | arr.reduce((acc,v)=>{}, init) | ❌ | 累積值 | 聚合、分組、扁平化、單趟多操作 | ⭐⭐⭐ |
for/for...of 會處理空位(值為 undefined)。for/while/for...of 支援 break/continue;函式式方法需拋出例外或改用 some/every(some 遇 true 中斷,every 遇 false 中斷)。forEach/map/filter/reduce 第 2 參數可綁定 this;箭頭函式自動捕獲外層 this。for / while / for...of 最快,避免函式呼叫開銷。forEach/map/filter 差異微乎其微。reduce 避免多次遍歷。// 只做副作用
users.forEach(u => u.save());
// 轉換資料
const names = users.map(u => u.name);
// 篩選
const adults = users.filter(u => u.age >= 18);
// 聚合/單趟多任務
const stats = users.reduce((acc, u) => {
acc.sum += u.score;
acc.max = Math.max(acc.max, u.score);
acc.byDept[u.dept] = (acc.byDept[u.dept] || 0) + 1;
return acc;
}, { sum: 0, max: -Infinity, byDept: {} });
選對遍歷方式,代碼更清晰、效能更優、Bug 更少。