JavaScript中删除数组元素:delete与splice的对比

JavaScript中删除数组元素:delete与splice的对比

技术背景

在JavaScript中,数组是常用的数据结构之一。有时我们需要从数组中删除元素,常见的方法有使用delete操作符和splice方法。但它们在使用方式和效果上存在显著差异。

实现步骤

使用delete操作符

delete操作符会删除数组元素对应的对象属性,但不会重新索引数组,也不会更新数组的长度。删除后,该位置会显示为undefined,但实际上是该属性被移除,数组变成“稀疏数组”。

1
2
3
4
5
let myArray = ['a', 'b', 'c', 'd'];
delete myArray[0];
console.log(myArray); // [empty, "b", "c", "d"]
console.log(myArray[0]); // undefined
console.log(myArray.length); // 4

使用splice方法

splice方法可以从数组中删除元素,并重新索引数组,同时会更新数组的长度。

1
2
3
4
let myArray = ['a', 'b', 'c', 'd'];
myArray.splice(0, 1);
console.log(myArray); // ["b", "c", "d"]
console.log(myArray.length); // 3

John Resig的Array.remove方法

John Resig创建了一个方便的Array.remove方法:

1
2
3
4
5
6
7
8
9
10
11
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};

// 使用示例
let array = ['a', 'b', 'c', 'd'];
array.remove(1); // 移除第二个元素
console.log(array); // ["a", "c", "d"]

使用filter方法

filter方法可以过滤掉不需要的元素,实现删除元素的效果。

1
2
3
let myArray = ['a', 'b', 'c', 'd'];
myArray = myArray.filter(x => x!== 'b');
console.log(myArray); // ["a", "c", "d"]

核心代码

移除数组中所有特定元素

1
2
3
4
5
6
7
8
9
10
11
12
13
// 使用splice
let items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];
while (items.indexOf('c')!== -1) {
items.splice(items.indexOf('c'), 1);
}
console.log(items); // ["a", "b", "d", "a", "b", "d"]

// 使用delete
items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];
while (items.indexOf('c')!== -1) {
delete items[items.indexOf('c')];
}
console.log(items); // ["a", "b", undefined, "d", "a", "b", undefined, "d"]

重新索引数组

1
2
3
4
5
6
7
8
9
10
11
function reindexArray(array) {
var result = [];
for (var key in array) {
result.push(array[key]);
}
return result;
}

let arr = [1, 2, undefined, 4];
arr = reindexArray(arr);
console.log(arr); // [1, 2, 4]

最佳实践

  • 当需要移除数组元素并重新索引数组时,建议使用splice方法。
  • 当只需要移除数组元素的属性,而不关心数组的连续性和长度时,可以使用delete操作符。
  • 如果要过滤掉数组中的特定元素,filter方法是一个简洁的选择。

常见问题

性能问题

在性能方面,splice方法在处理小和大数组时都比较快;delete操作符在处理大数组时最快,处理小数组时速度中等;filter方法在Chrome和Firefox中处理小数组时最快,但在Safari中较慢,且处理大数组时性能不佳。

delete操作符是否将元素设置为undefined

delete操作符不是将元素设置为undefined,而是完全移除该元素(属性),留下一个空缺。

如何选择合适的方法

根据具体需求选择:如果需要保持数组的连续性和更新长度,使用splice;如果只需要移除属性而不改变数组结构,使用delete;如果要过滤特定元素,使用filter


JavaScript中删除数组元素:delete与splice的对比
https://119291.xyz/posts/javascript-array-element-deletion-delete-vs-splice/
作者
ww
发布于
2025年7月16日
许可协议