如何在迭代集合时删除项目?
我想使用 AS“foreach”语法来循环项目集合。在循环中,我有时需要从正在迭代的集合中删除一个项目。
使用“for”循环,我会这样编码(注意“--”运算符将索引移回):
for (var n:int=0; n<ac.length; n++) {
var s:String = ac.getItemAt(n) as String;
if (s == 'c')
ac.removeItemAt(n--);
}
是否也可以使用“foreach”构造执行类似的操作?
I would like to use the AS "for each" syntax to loop over a collection of items. Within the loop I sometimes need to remove an item from the collection I am iterating over.
Using a "for" loop, I would code this like (note the "--" operator to move the index back):
for (var n:int=0; n<ac.length; n++) {
var s:String = ac.getItemAt(n) as String;
if (s == 'c')
ac.removeItemAt(n--);
}
Is it also possible to do something similar using a "for each" construct?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在我所知道的所有语言中,
foreach
要求它迭代的集合在迭代时不会改变。所以,简单的答案是——不,你不能。但您在示例中执行此操作的方式是可以的。
编辑:您可以做的是创建一个需要在 foreach(of itemList) 内删除的项目的新列表,然后通过另一个 foreach(of returnedItems) 并从 itemList 中删除。唯一需要担心的是您不会迭代正在更改的集合。
In all of the languages I know of, the
foreach
requires that the collection it iterates through does not change while iterating.So, the simple answer would be - no, you can't. But the way you're doing it in your sample is OK.
edit: What you could do is to create a new list of items that need to be deleted inside a foreach(of itemList), and than go through another foreach(of deletedItems) and remove from itemList. The only thing is to worry about is that you don't iterate over the collection you're changing.
复制您的
arraycollection
或数据结构。对原始内容执行反向 for 循环
并从复制的结构中删除所需索引处的元素。
输出:您的新数据结构减去您不想保留的元素。
Copy your
arraycollection
or your data structure. Do areverse for loop
on your originaland remove the elements at the required index from the copied structure.
Output: Your new data structure minus the elements you dont want to keep.
如果您正在讨论的 for every 构造允许在迭代期间访问索引,这是可能的,但即使如此,它也肯定会适得其反,因为我确信大多数语言都假设集合不会突然改变如果您使用
foreach
,则它在迭代期间的“长度”或其索引。如果您输入索引参数,那么您将回到常规的for
构造,因此整个练习最终会变得徒劳。It is possible if the
for each
construct you are talking about allows access to an index during the iteration but even then it is sure to backfire because I am certain most languages assume the collection is not suddenly going to change its "length" or its indices during the iteration if you are usingfor each
. If you put in a index parameter then you are back to a regularfor
construct so the whole exercise ends up being futile.这可以通过 for ... in 循环实现。迭代不会中断。
This is possible with the for ... in loop. The iteration is not disrupted.