JavaScript 陣列是現代 Web 開發中資料操作的支柱。隨著 ES2023 規範引入了長期變異方法的不可變替代方案,現在是重新審視我們如何使用陣列的最佳時機。本文涵蓋了數組方法的全部內容,從熟悉的“map”、“filter”和“reduce”到前沿的添加,並提供了實際範例和效能見解。
数组方法景观
數組方法分為兩大類:變異和非變異。 push、pop、splice、sort 和 reverse 等方法就地修改數組,而 map、filter、slice 和 ES2023 新增的方法則建立新陣列。行業趨勢正在轉向不變性,這可以減少由意外副作用引起的錯誤。
ES2023 引進了四種解決常見痛點的不可變方法:
const arr = [3, 1, 4, 1, 5, 9];
const sorted = arr.toSorted(); // [1, 1, 3, 4, 5, 9] — new array
const reversed = arr.toReversed(); // [9, 5, 1, 4, 1, 3] — new array
const spliced = arr.toSpliced(1, 2); // [3, 1, 5, 9] — new array
const updated = arr.with(2, 42); // [3, 1, 42, 1, 5, 9] — new array
console.log(arr); // [3, 1, 4, 1, 5, 9] — unmodified
這些方法使得在 React 或 Redux 等狀態管理上下文中使用陣列更加安全,其中不變性是核心原則。
深度映射、過濾和縮減
函數式陣列方法的三巨頭——「map」、「filter」和「reduce」——無需顯式循環即可實現富有表現力的資料轉換。
map 透過回呼函數轉換每個元素,產生一個相同長度的新陣列:
@@@代碼區塊1@@@
filter 選擇通過謂詞測試的元素:
const even = numbers.filter(n => n % 2 === 0);
// [2, 4]
「reduce」是最通用的——它可以實現任何其他方法:
const sum = numbers.reduce((acc, n) => acc + n, 0);
// 15
// map implemented with reduce
const squared2 = numbers.reduce((acc, n) => [...acc, n * n], []);
一個常見的反模式是當單一「flatMap」就足夠時,將「map」連結到「filter」。每個連結方法都會建立一個中間數組,這對於大型資料集很重要。
| 方法 | 返回 | 變異原創 | 使用案例 |
|---|---|---|---|
地圖 | 新陣列 | 沒有 | 改變每個元素 |
過濾器 | 新陣列 | 沒有 | 選擇元素子集 |
減少 | 任意值 | 沒有 | 聚合為單一值 |
排序 | 相同的陣列 | 是的 | 現場訂購 |
已排序 | 新陣列 | 沒有 | 不可變的排序 |
flatMap 和 groupBy
「flatMap」將映射和展平結合到一個通道中。當每個輸入元素映射到零個、一個或多個輸出元素時,它特別有用:
const sentences = ["hello world", "foo bar"];
const words = sentences.flatMap(s => s.split(" "));
// ["hello", "world", "foo", "bar"]
Object.groupBy (ES2024) 提供本機分組支援:
const users = [
{ name: "Alice", role: "admin" },
{ name: "Bob", role: "user" },
{ name: "Charlie", role: "user" },
];
const grouped = Object.groupBy(users, user => user.role);
// { admin: [{ name: "Alice", role: "admin" }],
// user: [{ name: "Bob", ... }, { name: "Charlie", ... }] }
這取代了先前必需的基於手動“reduce”的分組模式。
函数链模式
功能鏈將操作組成可讀取的管道:
const result = data
.filter(item => item.isActive)
.map(item => ({ ...item, score: item.value * 2 }))
.filter(item => item.score > 10)
.reduce((acc, item) => acc + item.score, 0);
鏈中的每個方法都會建立一個中間數組。對於少於 10,000 個元素的數組,此開銷可以忽略不計。除此之外,考慮使用單一“reduce”通道或轉換器庫(例如 Ramda)來消除中間分配。
效能考慮因素
簡單操作的循環效能通常遵循以下順序(最快的優先順序):「for」迴圈、「for…of」、「forEach」、「map」、「filter」、「reduce」。然而,可讀性應該是預設選擇——只有在分析發現瓶頸時才進行最佳化。
「find」方法受益於提前終止,並且可以比「filter」和索引存取快幾個數量級:
const found = arr.find(x => x.id === targetId); // O(n) average, stops early
const found2 = arr.filter(x => x.id === targetId)[0]; // O(n) always, full traversal
真實世界的食譜
使用“Set”可以優雅地處理刪除重複項:
const unique = [...new Set([1, 2, 2, 3, 3, 4])];
// [1, 2, 3, 4]
將數組分成組:
const chunk = (arr, size) =>
Array.from({ length: Math.ceil(arr.length / size) }, (_, i) =>
arr.slice(i * size, i * size + size)
);
Fisher-Yates 洗牌提供無偏差隨機化:
const shuffle = arr => {
const a = [...arr];
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
};
TypeScript 集成
正確的鍵入可以增強數組方法的使用。 filter 中的類型謂詞啟用類型縮小:
const items: (string | null)[] = ["a", null, "b", null];
const strings: string[] = items.filter((x): x is string => x !== null);
對於複雜的歸約,請提供明確的累加器類型:
const grouped = items.reduce<Record<string, number[]>>((acc, item) => {
(acc[item.key] ??= []).push(item.value);
return acc;
}, {});
不變性模式
ES2023 不可變方法(「toSorted」、「toReversed」、「toSpliced」、「with」)應該成為非效能關鍵程式碼的預設方法。它們消除了與突變相關的整個類別的錯誤,同時保持了可讀性。在狀態管理中,將它們與擴充運算子結合進行複雜的更新:
const state = { items: [1, 2, 3], selected: null };
const next = {
...state,
items: state.items.with(0, 99).toSorted(),
};
掌握陣列方法對於編寫乾淨、高效的 JavaScript 至關重要。從日常任務的“map”、“filter”和“reduce”開始,針對特定模式採用“flatMap”和“groupBy”,並儘可能預設使用 ES2023 不可變方法。

