數組是 JS 最常用的數據結構,原型上提供了豐富的方法。本文按功能分類系統梳理,附帶實戰技巧與現代最佳實踐。
| 方法 | 說明 | 返回值 |
|---|---|---|
| join(sep) | 元素轉字符串連接 | 字符串 |
| toString() | 調用 join(',') | 字符串 |
| toLocaleString() | 本地化連接 | 字符串 |
[1,2,3].join('-'); // "1-2-3"
[1,2,3].toString(); // "1,2,3"
[[1,2],[3,4]].join('|'); // "1,2|3,4" (內層調用 toString)
| 方法 | 操作位置 | 行為 | 返回值 |
|---|---|---|---|
| push(...items) | 末尾 | 添加 | 新長度 |
| pop() | 末尾 | 移除 | 移除項 |
| unshift(...items) | 頭部 | 添加 | 新長度 |
| shift() | 頭部 | 移除 | 移除項 |
const arr = [];
arr.push(1,2); // [1,2] 返回 2
arr.unshift(0); // [0,1,2] 返回 3
arr.pop(); // [0,1] 返回 2
arr.shift(); // [1] 返回 0
const arr = [3,1,2];
arr.reverse(); // [2,1,3]
arr.sort(); // [1,2,3] —— 字符串排序!
arr.sort((a,b)=>a-b); // 數值升序
arr.sort((a,b)=>b-a); // 數值降序
注意:默認 sort() 按字符串 Unicode 排序,數值必須傳比較函數。
const arr = [1,2,3,4,5];
arr.splice(2, 1); // 刪除索引2起1個 → [1,2,4,5] 返回 [3]
arr.splice(1, 0, 'a','b'); // 索引1插入 → [1,'a','b',2,4,5] 返回 []
arr.splice(2, 2, 'x'); // 索引2替換2個 → [1,'a','x',4,5] 返回 ['b',2]
splice(start, deleteCount, ...items) 是數組增刪改的萬能鑰匙。
const arr = [1,2,3,4,5];
arr.slice(1,3); // [2,3] 索引1到3(不含)
arr.slice(-3,-1); // [3,4] 負索引從末尾倒數
arr.concat([6,7]); // [1,2,3,4,5,6,7] 合併
arr.concat(8, [9]); // [1,2,3,4,5,8,9] 展開合併
| 方法 | 回調參數 | 返回值 | 特點 |
|---|---|---|---|
| forEach(fn) | (val, idx, arr) | undefined | 單純遍歷,不可中斷 |
| map(fn) | (val, idx, arr) | 新數組 | 一對一映射 |
| filter(fn) | (val, idx, arr) | 新數組 | 篩選,返回 true 保留 |
| every(fn) | (val, idx, arr) | boolean | 全真才 true |
| some(fn) | (val, idx, arr) | boolean | 一真即 true |
| reduce(fn, init) | (acc, val, idx, arr) | 累積值 | 歸約/聚合 |
| reduceRight(fn, init) | 同 reduce | 累積值 | 從右向左 |
const users = [
{name:'A', age:20, active:true},
{name:'B', age:25, active:false},
{name:'C', age:30, active:true}
];
// 活躍用戶名單
users.filter(u => u.active).map(u => u.name); // ['A','C']
// 年齡總和
users.reduce((sum, u) => sum + u.age, 0); // 75
// 按年齡分組
users.reduce((groups, u) => {
(groups[u.age] = groups[u.age] || []).push(u);
return groups;
}, {});
| 方法 | 說明 |
|---|---|
| find(fn) | 返回首個滿足條件的元素 |
| findIndex(fn) | 返回首個滿足條件的索引 |
| includes(val) | 是否包含值(支持 NaN) |
| flat(depth) | 扁平化嵌套數組 |
| flatMap(fn) | map 後扁平化 |
| from(iterable) | 類數組/可迭代對象轉數組 |
| of(...items) | 創建數組(修復 Array 构造函數陷阱) |
| at(index) | 支持負索引訪問 |
| with(index, val) | 返回新數組(不可變更新) |
| toSorted/reversed/spliced | 不可變版 sort/reverse/splice |
Array.isArray([]); // true(推薦,跨框架可靠)
[] instanceof Array; // true(同框架可靠)
Object.prototype.toString.call([]) === '[object Array]'; // 最通用
const sparse = [1,,3]; // 長度3,索引1為空位
sparse.forEach(x => console.log(x)); // 只輸出 1,3 —— 跳過空位
sparse.map(x => x*2); // [2, empty, 6] —— 保留空位結構
[...sparse]; // [1, undefined, 3] —— 展開填 undefined
數組方法分「修改原數組」與「返回新數組」兩大陣營。現代開發推薦不可變模式:優先用 map/filter/reduce/flatMap/toSorted 等純函數,配合展開運算符 ...arr,代碼更可預測、易測試、利於並發。掌握各方法參數、返回值、副作用,是寫好 JS 的基本功。