Tutorials, extensions, and source files for ActionScript, Flash, and other Adobe products.


I Lied - Array Iteration Order

Posted May 05, 2009 by senocular

Ok, I didn't necessarily "lie" per se, but I did leave out some vital information in one of my ActionScript 3.0 tips of the day, for..in and for each..in. There I claimed that ActionScript 3.0 "maintains array element order (using numeric array indices) when using for..in and for each..in". But does it?
The answer is yes and no. First of all the ECMAScript does not specify that they should. Then again, what good is that now? But more importantly, and something that I left out of the tip (now corrected, though admittedly, I doubt I knew this at the time I wrote it), was that array element order is only maintained for well formed dense arrays. In other words, order is maintained as long as you don't have any gaps between your array elements. For example:

var denseArray:Array = [];
denseArray[0] = "a";
denseArray[1] = "b";
denseArray[2] = "c";

var nonDenseArray:Array = [];
nonDenseArray[0] = "a";
nonDenseArray[6] = "b";
nonDenseArray[53] = "c";

For loops for the first array, denseArray, will consistently maintain order in Flash Player for ActionScript 3.0. Order will not be maintained for the second array, nonDenseArray. Order may come out that way, but it isn't guaranteed.

Of course at the same time, you probably really shouldn't be fully relying on the order for any case using for loops anyway.