按索引删除数组

时间:2013-07-19 15:04:44

标签: javascript arrays each

我在使用JS delete()函数时遇到了一些麻烦。

直接来自Chrome Inspector:

> 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

的问题

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

要从阵列中正确删除对象,您应该使用splice method

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

答案 2 :(得分:0)

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

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

delete()执行类似于将数组元素指定为undefined的操作。请注意,在使用delete()之后,数组不会移位且长度保持不变:

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

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

a.splice(0,1)

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

a.length -> 2

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