循环遍历数组并删除项目,而不会中断 for 循环 [英] Looping through array and removing items, without breaking for loop

查看:30
本文介绍了循环遍历数组并删除项目,而不会中断 for 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 for 循环,当我使用 splice() 删除项目时,我得到秒"未定义.我可以检查它是否未定义,但我觉得可能有一种更优雅的方法来做到这一点.愿望是简单地删除一个项目并继续.

I have the following for loop, and when I use splice() to remove an item, I then get that 'seconds' is undefined. I could check if it's undefined, but I feel there's probably a more elegant way to do this. The desire is to simply delete an item and keep on going.

for (i = 0, len = Auction.auctions.length; i < len; i++) {
    auction = Auction.auctions[i];
    Auction.auctions[i]['seconds'] --;
    if (auction.seconds < 0) { 
        Auction.auctions.splice(i, 1);
    }           
}

推荐答案

当您执行 .splice() 时,数组正在重新索引,这意味着您将跳过索引一个被删除,您缓存的 .length 已过时.

The array is being re-indexed when you do a .splice(), which means you'll skip over an index when one is removed, and your cached .length is obsolete.

要修复它,您需要在 .splice() 之后减少 i,或者简单地反向迭代...

To fix it, you'd either need to decrement i after a .splice(), or simply iterate in reverse...

var i = Auction.auctions.length
while (i--) {
    ...
    if (...) { 
        Auction.auctions.splice(i, 1);
    } 
}

这种方式重新索引不会影响迭代中的下一项,因为索引只影响从当前点到数组末尾的项,并且迭代中的下一项低于当前点.

This way the re-indexing doesn't affect the next item in the iteration, since the indexing affects only the items from the current point to the end of the Array, and the next item in the iteration is lower than the current point.

这篇关于循环遍历数组并删除项目,而不会中断 for 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆