Iterate Over An Object In Actionscript 3
A helper class to make iterating over objects easier. 2009-01-13
Did you ever do something like:
for(var key:String in myObject){
trace(key+"="+myObject[key];
}
in Actionscript 2?
Perhaps you noticed this stopped working in ActionScript 3 for strongly typed objects. It took me a while to notice, since I don't really do this very often. In Actionscript 3 you have to do some voodoo with the describeType() function to make the magic happen. But this is kind of annoying, plus describeType makes XML, and that's slow.
So I've created the Enumerator class, which helps you iterate over your properties in a strongly typed class.
package{
import flash.display.*;
import com.terralever.util.Enumerator;
public class EnumeratorDemo extends MovieClip
{
public var foo:String = "la de dah";
public var yippee:String = "dum de dum";
public function EnumeratorDemo()
{
trace("EnumeratorDemo...................");
var thing:StronglyTyped = new StronglyTyped("blah","bloop","bleep");
var e:Enumerator = Enumerator.create(thing);
var key:Object;
trace("Strongly typed object:");
while( key = e.next() )
{
trace(key +"="+thing[key]);
}
trace("Another strongly typed object:");
var e2:Enumerator = Enumerator.create(this);
while( key = e2.next() )
{
trace(key+"="+this[key]);
}
}
}
}
The enumerator class helps with creating an enumerator, which then helps you loop over your variables. It also stores the array of variables for re-use, so iterating over multiple objects of the same class type is more efficient.
Download the Enumerator class and demo code here
|