I recently ran into an issue where I had a foreach loop iterating over an ArrayCollection of objects. Inside the loop, I was doing a simple check to see if the current object contained a matching property, if it did, I then removed it from the collection. I soon realized that the number of elements being removed didn’t quite match up to what I would have expected. The cause was quite simple: When removing items from a collection, you update the length of that collection, which in-turn breaks your iteration. This seemed like a very common problem (which I found to be true after a bit of googling), and luckily there are a number of ways to solve this. The very simple solution which I ended up implementing is as follows:
Instead of using a foreach loop, I switched to using a for loop. I then iterate over the collection backwards so that any updates to its’ length have no effect on the iteration.
var myID:uint = 1;
// some code to add Objects to myCollection which
// contain an <em>id</em> property.
protected function removeByFor():void
var len:uint = myCollection.length-1;
for (var x:int = len; x >= 0; x--)
if( myCollection.getItemAt(x).id == myID )
myCollection.removeItemAt( x );
That’s all there is to it. It’s quite simply when you stop to think about it, but when banging out code at the speed of light, who has time to think.. ;-)