:::: MENU ::::
Posts tagged with: actionscript

AS3 – Removing Elements While Iterating Over an Array

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:

The Solution:
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.

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.. ;-)


Mastering property existence with the hasOwnProperty method

For a long time I’ve struggled with determining whether or not a property exists in Actionscript 3.0. Like many people, I would often find myself writing somewhat tediously repetitive conditional checks such as:

Other than the fact that this is a lot of code to write (especially when you have a long conditional that checks 10 or 15 properties), this would work “most” of the time. I say most, because if the property you were trying to validate didn’t exist at all (i.e. there is no property name “myProperty” in your object), then you would get a nice “null object reference” error.
Continue Reading