在数组元素上使用运算符与使用方法有delete什么区别?Array.splice
delete
Array.splice
例如:
myArray = ['a', 'b', 'c', 'd']; delete myArray[1]; // or myArray.splice (1, 1);
如果我可以像使用对象一样删除数组元素,为什么还要使用 splice 方法?
delete将删除对象属性,但不会重新索引数组或更新其长度。这使它看起来好像是未定义的:
> myArray = ['a', 'b', 'c', 'd'] ["a", "b", "c", "d"] > delete myArray[0] true > myArray[0] undefined
请注意,它实际上并未设置为 value undefined,而是从数组中删除了该属性,使其 看起来 未定义。emptyChrome 开发工具通过在记录数组时打印来明确区分。
undefined
empty
> myArray[0] undefined > myArray [empty, "b", "c", "d"]
myArray.splice(start, deleteCount)实际上删除元素,重新索引数组并更改其长度。
myArray.splice(start, deleteCount)
> myArray = ['a', 'b', 'c', 'd'] ["a", "b", "c", "d"] > myArray.splice(0, 2) ["a", "b"] > myArray ["c", "d"]