ActionScript 3's new loop

| 2 Comments | No TrackBacks

Did you know ActionScript 3 introduced a new loop construct? I discovered this while doing a lot of XML manipulation with E4X, and it's really a gem.

Along with the "for..in" loop, we now have at our disposal a "for each..in" loop. The two loops are very similar in style/syntax, but there's a subtle difference. Consider the following code snippet:

var arr:Array = ["test", "test2", "test3"]; // Use a regular for in loop to access the properties in arr for ( var i in arr ) { trace( i ); } // Use the new for each in loop to access the values in arr for each ( var s:String in arr ) { trace( s ); }

The first loop will trace values 0, 1, and 2. The for..in loop will loop over the property names in an object - in this case, we get the array indexes. In order to get the values in the array, we would have to "trace( arr[i] )".

The second loop will trace values test, test2, and test3. Notice the subtle difference here? Instead of getting the properties in an object, we get the property values. This is a handy shortcut, and is especially useful in dealing with XML in the E4X manner:

var data:XML = 12 61 hello ; for each ( var f:XML in data.foo ) { trace( f ); }

The above loop will out 12, 61, and hello.

Nothing earth shattering really, just something new to add to your bag of tricks... Enjoy!

No TrackBacks

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

2 Comments

  • makes debugging alot easier i think.

     
  • Well that's a good one - i use that often in php. I mean, how often did you have to do a 'for (var i in n)' and all you needed was the n[i], not the i. For me: often! So that's a highly appreciated syntax addition really. :-)

     

Leave a comment

Flex.org - The Directory for Flex

Archives