有一個陣列 var arr = ['a','b','c'],要刪掉其中的 'b',做法不只一種,而它們對「長度」與「索引」的影響完全不同。
delete arr[1];
陣列長度不變(仍是 3),arr[1] 變成 undefined,但其他元素的索引保持原位。這對「不想讓索引位移」的場景是好事。遍歷時用 for...in 會自動跳過被刪掉的槽:
for (var index in arr) {
document.write('arr[' + index + ']=' + arr[index]);
}
注意 for...in 不保證順序,且會列出自訂屬性,一般情境請改用 Object.keys 或 forEach(forEach 會跳過稀疏槽位)。delete 在 IE4.0 之後都支援。
arr.splice(1, 1);
第一個參數是起始索引(從 0 算起),第二個是刪除的個數,這裡就是移除第二個元素 'b'。長度變成 2,後面的元素索引往前補,因此可以用普通的 for 迴圈遍歷。splice 在 IE5.5 以後才支援。
splice 還能同時插入:arr.splice(1, 1, 'd', 'e') 會移除 'b' 並在該位置放入 d、e,結果是 a, d, e, c。這是它比 delete 強的地方——「刪除+插入」一次完成。
設定 length 是唯一能真正縮短陣列長度的原生方式,若要一次砍掉尾端多個元素,arr.length = 2 比迴圈快得多。
// 以迴圈重組:把不等於目標索引的元素往前搬
Array.prototype.remove = function (dx) {
if (isNaN(dx) || dx > this.length) { return false; }
for (var i = 0, n = 0; i < this.length; i++) {
if (this[i] != this[dx]) { this[n++] = this[i]; }
}
this.length -= 1;
};
// 用 splice 實作,程式碼短得多
Array.prototype.baoremove = function (dx) {
if (isNaN(dx) || dx > this.length) { return false; }
this.splice(dx, 1);
};
早期 IE5 的 Array 沒有現成刪除方法,IE5.5 的 splice 又常被誤解為「只是把值清空」,因此才需要自己擴充。用 slice + concat 也能做到,而且不改動原陣列:
Array.prototype.del = function (n) {
if (n < 0) { return this; }
// slice 取頭段與尾段,concat 起來剛好少了第 n 項
return this.slice(0, n).concat(this.slice(n + 1, this.length));
};
var test = [0, 1, 2, 3, 4, 5];
test = test.del(3); // 移除索引 3(第 4 項)
alert(test); // 0,1,2,4,5
現在不必再擴充 Array.prototype(那會污染全域,且可能與其他函式庫衝突)。依需求選即可:要移除並補位用 splice;要清空某個位置保留索引用 delete;要一次砍尾端用 length;要保留原陣列的純函式風格用 slice + concat 或 filter。依值刪除時,arr.indexOf('b') 找到位置再 splice,或直接 arr.filter(x => x !== 'b'),都比自訂方法清楚。