inicio mail me! sindicaci;ón

t-roy.net*

blog by designer troy ginbey

for.. each.. in

For each in is a handy statement to iterate over items in a collection (or object), and execute statements on those items – for example, an Object, Array, or XML. I’ll give an example of each of these…

Object
var myObject:Object = {name:"Shofferhoffer", type:"Wheat Beer", alcoholPercentage:4.5, origin:"Germany"}
for each (var item in myObject) {
trace(item);
}

outputs:
4.5
Germany
Shofferhoffer
Wheat Beer

Array
var myArray:Array = new Array("Corona", "Shofferhoffer", "Fosters");
for each (var item in myArray) {
trace(item);
}

outputs:
Corona
Shofferhoffer
Fosters

XML
var myXML:XML = <drinks><wine>merlot</wine><wine>shiraz</wine><beer>wheat beer</beer><beer>ale</beer><beer>lager</beer>;
for each (var item in myXML.beer) {
trace(item);
}

outputs:
wheat beer
ale
lager

The for each..in statement iterates only through the dynamic properties of an object, not the fixed properties. And unlike the for..in statement, the for each..in statement iterates over the values of an object’s properties, rather than the property names.

So, there’s a few good usage examples for for.. each.. in. Worth keeping in mind when working with objects!

2 Comments »

  whodeee wrote @ April 30th, 2009 at 5:05 am

Thanks for the helpful hints with the “for each” statements
FYI – I wanted to let you know that I don’t think your XML example is displaying properly – it is missing the node names and the symbols.

  T-roy wrote @ June 13th, 2009 at 10:06 pm

Thanks whodeee! Fixed.

Your comment

HTML-Tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>