Wednesday, April 7, 2010

AS3: "for..in" and "for each...in" statements


After trolling browsing the awesome Grant Skinner's Flash dev blog (gskinner.com/blog/) I came across an interesting bit of actionscript that up until now I was completely unaware of.

Let's say for example that you have set up an object containing the following data:


var myObject:Object = new Object();

myObject.name = "Ben";
myObject.age = 32;
myObject.married = true;


How would you retrieve this data in a manner other than referencing the objects children directly (ie "myObject.name") ... Here's how...

for each (var value:* in myObject) {

      trace(value);
}

The above use of the "for each...in" code pumps out the following in your tracer window:


Ben

True
32

On the other hand, say that I want to obtain the name of the object child that these values are associated with... simply remove the word "each" from the iteration statement and it reports on the actual child variable instead of the child variables value...


for (var pos:String in myObject) {

     trace(pos);
}


The resulting output to the tracer will be:

name

married
age 

You could even go one step further to retrieve the values of each variable in the myObject object as follows...



for (var pos:String in myObject) {
     trace(myObject[pos]);
}


The above will output:

Ben

True
32

Nice little twist on an iteration statement, eh?