Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For-Each Loop AS3: Is the direction guaranteed?

I would like to know the iteration order for the Array, Dictionary and Object types in AS3, for both the for-each and the for-in loops. Also what factors can change the iteration order of these loop type combinations?

For example I presume that using a for-each on an Array type always move from the first element to the last. For-each cannot be used on a Dictionary so how is the order determined using a for-in loop?

like image 232
BefittingTheorem Avatar asked Mar 06 '09 14:03

BefittingTheorem


3 Answers

As stated in Essential Actionscript 3.0 by Colin Moock, the order of a for each in loop is not guaranteed unless enumerating an XML or XMLList object;

Click here for Colin Moock's words from his book.

There are workarounds as discussed here, but honestly if you need to guarantee the order then just use a regular old for loop and have it iterate (length, numChildren, etc.) number of times.

like image 59
Brian Hodge Avatar answered Nov 13 '22 10:11

Brian Hodge


Do you mean the for (x in y) type of for-each loop? The AS3 specification says that for loops "have the same syntax and semantics as defined in ECMA-262 edition 3 and E4X".

ECMA-262, section 12.6.4 state that "the order of enumeration is defined by the object" - in other words, it will depend on whether you're iterating through a list, a dictionary, an array etc.

I would hope that the documentation for most collections will explicitly state the enumeration order (or that the order isn't defined) but I haven't checked...

EDIT: Unfortunately the specs state that "the mechanics of enumerating the properties [...] is implementation dependent." I can't see anything in the Array docs to specify ordering. It's a bit unsatisfactory, to be honest :(

like image 5
Jon Skeet Avatar answered Nov 13 '22 10:11

Jon Skeet


The order of evaluation changed in AS3.0 Earlier, in AS 1.0 and 2.0, the order of evaluation was based on the order in which the objects were added. Now, in 3.0, all looping maintains array order. Try the snippet:

var a:Array = new Array();
a[ 1 ] = 'first';
a[ 0 ] = 'second';

for (var key:String in a) 
    trace( key + ': ' + a[ key ] );

Try the above with AS3.0 and AS1.0/2.0

like image 2
dirkgently Avatar answered Nov 13 '22 10:11

dirkgently