How to remove an item while iterating over collection?
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 thi开发者_运维技巧s 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?
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.
Copy your arraycollection
or your data structure. Do a reverse for loop
on your original
and remove the elements at the required index from the copied structure.
Output: Your new data structure minus the elements you dont want to keep.
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 using for each
. If you put in a index parameter then you are back to a regular for
construct so the whole exercise ends up being futile.
This is possible with the for ... in loop. The iteration is not disrupted.
var o:Object = { a: 0, b: 1, c:2 };
for (var k:String in o)
{
delete o[k];
}
精彩评论