數組是 JS 最核心的數據結構。ES5/ES6/ES2023 不斷擴充方法,舊教程易過時。本文系統梳理 3 大屬性、8 大分類 30+ 方法、常見陷阱與現代函數式風格最佳實踐,構建完整知識體系。
const arr = [1, 2, 3];
arr.length; // 3
arr.length = 5; // [1, 2, 3, empty × 2] 稀疏數組
arr.length = 1; // [1] 元素被截斷
arr[10] = 99; // length 自動變為 11,中間空位為 empty
陷阱:empty 槽位 forEach/map/filter 會跳過,for...of 會遍歷為 undefined。
// 僅教學示例,生產環境禁用
Array.prototype.first = function() { return this[0]; };
[1,2,3].first(); // 1
// 現代替代:獨立函數 / 模組導出
export const first = arr => arr[0];
[].constructor === Array; // true
new Array().constructor === Array; // true
// 用途:檢測是否為數組(但推薦 Array.isArray())
| 分類 | 方法 | 是否改變原數組 | 返回值 |
|---|---|---|---|
| 創建/轉換 | Array.from() | 否 | 新數組 |
| Array.of() | 否 | 新數組 | |
| Array.isArray() | 否 | Boolean | |
| Array.prototype.at() | 否 | 元素/undefined | |
| 增/刪/改 (變異) | push() | ✅ | 新長度 |
| pop() | ✅ | 被刪元素 | |
| unshift() | ✅ | 新長度 | |
| shift() | ✅ | 被刪元素 | |
| splice() | ✅ | 被刪元素數組 | |
| sort() | ✅ | 原數組引用 | |
| 合併/切片 (非變異) | concat() | 否 | 新數組 |
| slice() | 否 | 新數組 | |
| 查找/檢測 (非變異) | indexOf() / lastIndexOf() | 否 | 索引/-1 |
| includes() | 否 | Boolean | |
| find() / findIndex() | 否 | 元素/索引 | |
| findLast() / findLastIndex() (ES2023) | 否 | 元素/索引 | |
| filter() | 否 | 新數組 | |
| some() / every() | 否 | Boolean | |
| flat() / flatMap() | 否 | 新數組 | |
| 遍歷/迭代 (非變異) | forEach() | 否 | undefined |
| map() | 否 | 新數組 | |
| reduce() / reduceRight() | 否 | 累積值 | |
| keys() / values() / entries() | 否 | Iterator | |
| for...of | 否 | — | |
| with() (ES2023) | 否 | 新數組 | |
| 轉換/序列化 | join() | 否 | String |
| toString() / toLocaleString() | 否 | String | |
| toReversed() / toSorted() / toSpliced() (ES2023) | 否 | 新數組 | |
| 填充/複製 | fill() | ✅ | 原數組 |
| copyWithin() | ✅ | 原數組 |
const users = [
{id:1, name:'Alice', age:25, active:true},
{id:2, name:'Bob', age:30, active:false},
{id:3, name:'Charlie', age:35, active:true}
];
// 鏈式:過濾 → 映射 → 排序 → 取前 N
const topActive = users
.filter(u => u.active)
.map(u => ({ label: u.name, value: u.id }))
.sort((a, b) => b.value - a.value)
.slice(0, 2);
// 分組
const byAgeGroup = users.reduce((acc, u) => {
const key = u.age < 30 ? 'young' : 'senior';
(acc[key] = acc[key] || []).push(u);
return acc;
}, {});
// 去重 (對象數組按 id)
const unique = users.reduce((acc, u) => {
if (!acc.map.has(u.id)) { acc.map.set(u.id, true); acc.arr.push(u); }
return acc;
}, { map: new Map(), arr: [] }).arr;
// 求和/平均
const avgAge = users.reduce((sum, u) => sum + u.age, 0) / users.length;
const nested = [1, [2, [3, 4]], 5];
nested.flat(2); // [1,2,3,4,5] 深度 2
nested.flat(Infinity); // 完全扁平
// flatMap = map + flat(1)
const sentences = ['Hello world', 'JS is fun'];
sentences.flatMap(s => s.split(' ')); // ['Hello','world','JS','is','fun']
const arr = [1, 2, 3, 4, 5];
arr.findLast(x => x > 2); // 5 (從後向前)
arr.findLastIndex(x => x > 2); // 4
arr.at(-1); // 5 (負索引從後)
arr.at(-2); // 4
const arr = [3, 1, 2];
arr.toSorted(); // [1,2,3] 原數組不變
arr.toReversed(); // [2,1,3]
arr.toSpliced(1, 1, 99); // [3,99,2] 索引1刪1項插入99
arr.with(0, 99); // [99,1,2] 索引0替換為99
| 陷阱 | 錯誤代碼 | 正確做法 | 原因 |
|---|---|---|---|
| forEach 中 return 不能中斷 | arr.forEach(x => { if(x>2) return; }) | 用 for...of + break / some()/every() | forEach 無中斷機制 |
| map 未返回值產生 undefined | arr.map(x => { x*2; }) | arr.map(x => x*2) 或 { return x*2; } | 箭頭函數塊語法需显式 return |
| sort() 默認字符串排序 | [10,2].sort() → [10,2] | [10,2].sort((a,b)=>a-b) | 轉字符串比較 "10" < "2" |
| splice 返回被刪元素非新數組 | const b = a.splice(1,1) | const b = [...a]; b.splice(1,1) | splice 變異原數組 |
| 稀疏數組遍歷差異 | [,,3].map(x=>x*2) → [empty,empty,6] | 用 flat()/filter() 處理空槽 | map 跳過 empty 槽 |
| arguments/NodeList 非數組 | arguments.map(...) | Array.from(arguments).map(...) | 類數組無數組方法 |
forEach < for...of < for (let i=0; i (極端大數據) push 比 unshift 快得多 (無需移動現有元素)Array.from(arrayLike, mapFn) 合併映射與轉換,避免中間數組Deque 數據結構或 LinkedList 庫
// 元組類型
const tuple: [string, number] = ['a', 1];
// 只讀數組
const readonly: ReadonlyArray = [1,2,3];
// readonly.push(4) // ❌ 編譯錯誤
// 非空數組 (需運行時斷言)
function head(arr: readonly [T, ...T[]]): T { return arr[0]; }
map/filter/reduce/concat/slice/toSorted...),減少副作用find,找索引用 findIndex,判斷存在用 includes/somefindLast/at/with/toSorted/toReversed/toSpliced 讓不變操作更直觀sort 字符串排序、forEach 不可中斷、稀疏數組跳過、splice 返回值誤解uniqBy, groupBy, chunk, shuffle) 納入團隊共享庫數組方法記不住沒關係,常用就那 10 個:map/filter/reduce/find/findIndex/includes/some/every/flat/flatMap。其餘查 MDN 或 IDE 提示即可。重點是建立「數據流轉換」思維,而非死記 API。