在JavaScript中删除数组元素 - 删除vs splice [英] Deleting array elements in JavaScript - delete vs splice
问题描述
使用 删除数组元素上的
运算符,而不是使用 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开发工具通过在记录数组时打印空
来清除此区别。
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"]
< a href =https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/splice =noreferrer> 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 splice的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!