javascript splice skipping element- why this behaviour

后端 未结 3 828
梦如初夏
梦如初夏 2021-01-29 06:07

I was working with splice within a nested for loop and I came across a behaviour I could not understand.

var a = [0, 1, 2, 3, 4];

for (b in a) {
           


        
3条回答
  •  北恋
    北恋 (楼主)
    2021-01-29 06:38

    You should not use for…in-enumerations to loop arrays.

    That said, your problem is that the .splice method modifies your array, removing an item and adjusting indizes after it. Yet, you do not adjust your iteration variable, so it will skip the index - the old index "1" was visited already, next will be "2" not the new "1" again.

    To solve this, you can either loop backwards or decrease the iteration counter by the number or removed items. However, when revisiting the index your condition would always be fulfilled, and you are successively removing all second elements from the arrays until there is no second element left - not sure whether this is your goal.

提交回复
热议问题