tutorials flash parcours

Different ways of traversing an array

We all know the for (loop) syntax which allows us to traverse the contents of an array with the help of a counter variable and a conditon :

var firstNames:Array = ["Eric","Stéphane","Paul","Sylvain"];
for(var i = 0; i < firstNames.length; i++) {
	trace(firstNames[i]);
}

output window:

Eric
Stéphane
Paul
Sylvain

Or even the for..in syntax which allows traversing an array by providing – with each step – the current position in the array. But beware in AS2, this traverses the array in reverse :

for(var index in firstNames) {
	trace(firstNames[index]);
}

With this, you can also traverse the properties of an object, but that’s another subject…

A new command has arrived in AS3, the for each command which allows you to traverse an array with the added advantage of providing you at each step, not only the current position in the array, but also the value stored in the array at that position:

for each(var value in firstNames) {
	trace(value);
}

very practcical when using XML:

var employeeXML:XML = <employees>
                    <name>Eric</name>
					<name>Stéphane</name>
					<name>Paul</name>
					<name>Sylvain</name>
                </employees>;
 
for each(var v:Object in employeeXML.name) {
	trace(v);
}

We have just seen here the 3 commands which allow us to traverse arrays. But the new AS3 framework also brings some new features along with it.

The Array class now includes a forEach method which allows us to traverse not only the contents of an array but also to execute a callback method (which we provide) on each element in the array.

This allows us to format the output depending on the content:

var blogsXML:XML = <blogs>
                    <blog author="Eric" langauge="C#" />
                    <blog author="Paul" language="AS3" />
                    <blog author="Sylvain" language="Java" />
                </blogs>;
var blogXMLList:XMLList = blogsXML.blog;
var blogsArray:Array = new Array();
for each (var b:XML in blogXMLList) {
	blogsArray.push(b);
}
blogsArray.sortOn("@author");
blogsArray.forEach(displayBlog);
 
function displayBlog(element:*, index:Number, arr:Array):void {
	trace(element.@auteur + ((element.@langage == "AS3") ? " – Crazy !" : ""));
}

output window:

Eric
Paul - Crazy!
Sylvain

By ITERATIF - BUGALOTTO Olivier (2006) You can find this tutorial and its comments on my blog








Adobe Training center


Mediabox Training Centre © 2000 - 2008 All rights reserved.
Adobe Authorized Training Centre. State convention under number 25 14 02167 14.
Mediabox : SARL au capital de 62.000€ - Activity number: 25 14 02167 14 - SIRET : 493 716 468 00027
MEDIABOX, 102 Avenue des Champs Elysées, 75008 PARIS - Tel. +33(0)2.31.91.96.89 - Fax. +33(0)2.72.68.56.42