Subtle Change in for..in Loops for ActionScript 3

| 2 Comments | No TrackBacks

There's a reason that you shouldn't rely on undocumented features. The for..in loop's behavior has changed from ActionScript 2 to ActionScript 3. It's a subtle change, but it might break your code.

The for..in loop iterates over the properties of an object. In previous versions of ActionScript, the for..in loop was known to iterate over the properties backwards, in a predictable order. It has been said many times that the order is not guaranteed, but in practice it was always the same, and predictable.

For example, the following code creates an object in ActionScript 2, adds some properties to the object, and then iterates over the properties with for..in. The order of the trace output is always the same:

var o:Object = new Object();
o.prop1 = 1;
o.prop2 = 2;
o.prop3 = 3;
o.prop4 = "four";

for ( var i:String in o ) {
	trace( i + ":" + o[i] );	
}

/* Always Displays:
prop4:four
prop3:3
prop2:2
prop1:1
*/

As an aside, in this type of situation I'd build the object with an object literal (using { prop1:1, prop2:2 ..etc.. }) instead of adding properties like the preceding code block, but the code was written this way for clarity. You can cleary see that the last item added is always the first one found by the for..in loop.

Because the order was always the same, you may have tried to use this to your advantage. However, in ActionScript 3 the same code does not produce the same results. The order of for..in is no longer predictable:

var o:Object = new Object();
o.prop1 = 1;
o.prop2 = 2;
o.prop3 = 3;
o.prop4 = "four";

for ( var i:String in o ) {
	trace( i + ":" + o[i] );	
}

/* Displays:
prop2:2
prop4:four
prop1:1
prop3:3
*/

/* Or, could Display:
prop3:3
prop2:2
prop1:1
prop4:four
*/

As you can see, if you used the undocumented feature of the for..in loop iterating backwards through an object, your code will not work the same in ActionScript 3. This demonstrates another good reason why undocumented features should be used with caution, as future versions are free to change functionality without warning.

No TrackBacks

TrackBack URL: http://www.darronschall.com/mt/mt-tb.cgi/89

2 Comments

There must be some other rule under cover - we just have to figure it out ;)

try for in after you have sorted the array and tell me again it is predictable in as2 :)

a = [1,5,3,5,7];
a.sort();
for(var i in a){
trace([i,a[i]]);
}

Cheers,
Ralf.

Leave a comment



About this Entry

This page contains a single entry by darron published on February 3, 2006 9:43 AM.

ActionScript 3 Klondike Solitaire Sample Application was the previous entry in this blog.

Reminder: Central Penn CFUG meeting tonight is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Archives

OpenID accepted here Learn more about OpenID
Powered by Movable Type 5.02