开发者

How to properly list items from array after splice

I have some example code:

var array = [];
array[0] = {id:0};
array[1] = {id:1};
array[2] = {id:2};

Now array looks like

[Object{id=0}, Object{id=1}, Object{id=2}] 

I use splice:

array.splice(0,1);

And we have:

[Object{id=1}, Object{id=2}]

When I try for or for ... in length will be only 2 and I can't iterate it in normal way. Result of loop is:

undefined
Object{id:1}  

In first case (when we use for) I understand why it didn't work, but for ... in should return indexes 1开发者_JAVA技巧 and 2 not 0 and 1...

Anybody can explain me what I am doing wrong?


What did you try? If I issue

var array = [];
array[0] = {id:0};
array[1] = {id:1};
array[2] = {id:2};
array.splice(0,1);
for (var i = 0, len = array.length; i < len; i++)
    console.log(i + ":", array[i]);

the engine correctly outputs

0: Object { id=1 }
1: Object { id=2 }

(but the array indices change to 0 and 1, perhaps that is what confuses you; remember that Array.splice by default removes from element 0 onwards and shifts all remaining elements downwards).

Update: apart from the fact that you can always get the id property of the individual objects using array[i].id, you can delete array elements without shifting the other elements using the delete operator. After I replace array.splice(0,1) with

delete array[0];

the output shows

0: undefined
1: Object { id=1 }
2: Object { id=2 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜