Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
455 views
in Technique[技术] by (71.8m points)

javascript - 遍历数组并删除项目,而不会中断循环(Looping through array and removing items, without breaking for loop)

I have the following for loop, and when I use splice() to remove an item, I then get that 'seconds' is undefined.(我有以下for循环,当我使用splice()删除项目时,然后得到“ seconds”是不确定的。)

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); } }   ask by dzm translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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() ,该数组将重新索引,这意味着删除索引时将跳过索引,并且缓存的.length已过时。)

To fix it, you'd either need to decrement i after a .splice() , or simply iterate in reverse...(要修复它,您需要在.splice()之后减少i ,或者简单地反向迭代...) 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.(这样,重新索引不会影响迭代中的下一个项目,因为索引仅影响从当前点到数组末尾的项目,并且迭代中的下一个项目低于当前点。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...