问题描述
我有以下for循环,当我使用 splice()
删除一个项目时,我得到'seconds'是未定义的。我可以检查它是否未定义,但我觉得这可能是一种更优雅的方式。希望简单地删除一个项目并继续前进。
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.
要修复它,您需要递减 i
在 .splice()
之后,或者只是反向迭代......
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.
这篇关于循环遍历数组并删除项目,而不会破坏循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!