使用 删除数组元素上的运算符,而不是使用 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"]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中删除数组元素
发布评论