在 JavaScript 中删除数组元素 - 删除 vs 拼接 [英] Deleting array elements in JavaScript - delete vs splice
问题描述
使用delete<有什么区别数组元素上的/code> 运算符
,而不是使用 Array.splice
方法?
What is the difference between using the delete
operator on the array element as opposed to using the Array.splice
method?
例如:
myArray = ['a', 'b', 'c', 'd'];
delete myArray[1];
// or
myArray.splice (1, 1);
如果我可以像删除对象一样删除数组元素,为什么还要使用 splice 方法?
Why even have the splice method if I can delete array elements like I can with objects?
推荐答案
delete
将删除对象属性,但不会重新索引数组或更新其长度.这使它看起来好像是未定义的:
delete
will delete the object property, but will not reindex the array or update its length. This makes it appears as if it is undefined:
> myArray = ['a', 'b', 'c', 'd']
["a", "b", "c", "d"]
> delete myArray[0]
true
> myArray[0]
undefined
请注意,它实际上并未设置为值 undefined
,而是从数组中删除了该属性,使其出现未定义.Chrome 开发工具通过在记录数组时打印 empty
来明确区分.
Note that it is not in fact set to the value undefined
, rather the property is removed from the array, making it appear undefined. The Chrome dev tools make this distinction clear by printing empty
when logging the array.
> myArray[0]
undefined
> myArray
[empty, "b", "c", "d"]
myArray.splice(start, deleteCount)
实际上是删除元素,重新索引数组,并改变其长度.
myArray.splice(start, deleteCount)
actually removes the element, reindexes the array, and changes its length.
> myArray = ['a', 'b', 'c', 'd']
["a", "b", "c", "d"]
> myArray.splice(0, 2)
["a", "b"]
> myArray
["c", "d"]
这篇关于在 JavaScript 中删除数组元素 - 删除 vs 拼接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!