按索引删除数组

Delete array by index

本文关键字:数组 删除 索引      更新时间:2023-09-26

JS delete()函数有点问题。

直接来自Chrome检查器:

> x = [{name: 'hello'}, {name: 'world'}]
> [Object, Object]
> delete x[0]
> true
> $.each (x, function (i, o) {console.log(o.name);})
> TypeError: Cannot read property 'name' of undefined
> x
> [undefined × 1, Object]

你知道为什么会发生这种事吗?它给我带来了each 的问题

删除x[0]与从数组中切片该条目不同。换句话说,元素1仍然处于x[1],因此x[0]undefined

要正确地从数组中删除对象,应该使用splice方法。

x = [{name: 'hello'}, {name: 'world'}];
x.splice(0,1);

数组数据结构上的delete()方法有点误导。当您执行以下操作时:

var a = ['one', 'two', 'three'];
delete a[0];

delete()的作用类似于将数组元素分配给undefined。注意,使用delete()后,数组不会移位,长度保持不变:

a.length -> 3
a[0] -> undefined

因此,从本质上讲,delete()创建了一个稀疏数组,不会更改length属性,也不会删除元素。要完全删除元素,您需要执行以下操作:

a.splice(0,1)

这将删除元素并更改数组的长度属性。所以现在:

a.length -> 2

有关方法参数的详细信息,请参见splice方法。