陣列操作是 JavaScript 開發的高頻場景,其中「刪除元素」看似簡單,實則暗藏多種語義與效能差異。本文系統梳理 delete、splice、filter、pop/shift、自訂原型擴展等 5 大類方法,並對比其對陣列長度、索引、稀疏陣列的影響,助你根據場景選擇最優方案。
const arr = ['a', 'b', 'c'];
delete arr[1]; // 刪除索引 1
console.log(arr); // ['a', empty, 'c']
console.log(arr.length); // 3(長度不變)
console.log(1 in arr); // false
特點:
for...in 會跳過空位,forEach/map 亦會跳過const arr = ['a', 'b', 'c'];
arr.splice(1, 1); // 從索引 1 刪除 1 個
console.log(arr); // ['a', 'c'],長度變為 2
// 同時刪除並插入
arr.splice(1, 1, 'd', 'e'); // ['a', 'd', 'e', 'c']
參數:start, deleteCount, ...items
const arr = ['a', 'b', 'c', 'b'];
const result = arr.filter(item => item !== 'b');
console.log(result); // ['a', 'c'],原陣列不變
const arr = ['a', 'b', 'c'];
arr.pop(); // 刪除尾部 'c',返回 'c'
arr.shift(); // 刪除頭部 'a',返回 'a'
// 基於 splice 的移除(按索引)
Array.prototype.removeAt = function (index) {
if (isNaN(index) || index < 0 || index >= this.length) return false;
this.splice(index, 1);
return this;
};
// 基於值的移除(刪除首個匹配)
Array.prototype.remove = function (value) {
const idx = this.indexOf(value);
if (idx !== -1) this.splice(idx, 1);
return this;
};
// 使用
['a','b','c'].removeAt(1); // ['a','c']
['a','b','c'].remove('b'); // ['a','c']
⚠️ 注意:修改內建原型易造成命名衝突、破壞 for...in 遍歷、影響第三方庫。現代專案建議改用獨立工具函式或 lodash.remove。
| 方法 | 是否改變原陣列 | 長度變化 | 索引重排 | 適用場景 |
|---|---|---|---|---|
| delete | 是(值變 empty) | 否 | 否 | 需保留索引位置 |
| splice | 是 | 是 | 是 | 通用刪除、插入、替換 |
| filter | 否(新陣列) | 是 | 是 | 函數式、條件批量刪除 |
| pop/shift | 是 | 是 | 是 | 首尾刪除、堆疊/佇列 |
| slice + concat | 否(新陣列) | 是 | 是 | 不污染原陣列的索引刪除 |
splice 或 filter;要「保留坑位」用 delete。delete,後續 JSON.stringify、map 等易產生預期外行為。splice 原地操作記憶體效率最高;若需不可變資料,filter 配合結構共享庫(如 Immer)更佳。filter 獲得完整型別推導,或封裝型別安全的 removeAt(arr, index) 工具函式。理解各刪除方法對陣列結構的實際影響,是寫出健壯、高效能 JavaScript 代碼的基礎。根據業務語境選擇正確工具,而非習慣性使用單一 API,能有效減少難以排查的索引偏移 Bug。