Iterating over an array with “holes” in JavaScript

前提是你 提交于 2021-02-10 21:59:51

问题


I have got an array from which some items are going to be removed; but some loops are still running on them, so I want to simply skip the places where I remove my objects

I know that the syntax for(i in array) should do this because it iterates on the index, but how should I remove my items then ? Because when i do array[4] = null, my for just doesn't care and goes on trying to use the value at 4.

I also tried to check if !null but without success... thank you


回答1:


If you want to remove an item without leaving a hole, you should use .splice()

myarray.splice(idx, 1);

But if you're saying that you want the holes there, but want to skip them, then you can use delete to remove the item (leaving a hole), and use .forEach() for the iteration, which skips holes.

delete myarray[idx];

// ...

myarray.forEach(function(item, i) {
    // holes will be skipped
});

To support older browsers like IE8 and lower, you'll need to add a compatibility patch for forEach().

  • MDN .forEach() (Ignore the shorter patch. It's a poor non-compliant version.)


来源:https://stackoverflow.com/questions/13847769/iterating-over-an-array-with-holes-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!