I have been working with ActionScript for a long time. And I have to admit I don’t know if the reason I never noticed some of the functionality was it was added after I read the documentation, or if I just never looked close enough to pick it up. But never the less I find that I have been overlooking some gems that are built in and so I wanted to make sure that you are not overlooking them as well.

I have been writing a lot of ruby lately and I really like the syntax for looping over each item in an array. In Actionscript there are several ways to do this: for loops, for each, for each in, and while. But each of those takes more setup and management then I think should be required. What I really wanted was to be able to call:

array.each( functionName );

And that would call the function that I pass into the each method of the array, once for every element. Turns out this functionality is actually available on the Array class of Actionscript. Its called forEach. You can use it by providing the forEach method a reference to a function with a signature that looks like this `functionName(item:*, index:int, arr:Array):void`, where item is the current element in the array, index is the current items index and arr is a reference to the array being used. Some example code that uses this could look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
private var list:Array = ['One','Two','Three'];
 
private function doSomethingToList():void
{
    list.forEach(output);
}
 
private function output(item:*, index:int, arr:Array):void
{
    trace(item);
}
 
doSomethingToList()

That would cause each of the items on the array to be traced to the console. So much nicer than a for loop. But it is still a bit more code so you could shorten that up like:

1
2
3
4
private function doSomethingToList():void
{
    list.forEach(function(item:*, index:int, arr:Array):void{trace(item)});
}

Or even chop it down a bit more using the rest array:

1
2
3
4
private function doSomethingToList():void
{
    list.forEach(function(... rest ):void{trace(rest[0])});
}

So the morale of the story is that even if you think you know how something works, it can never hurt to take a look at the docs and confirm that. :) And if you like forEach make sure you check out: every, join, map, some and splice.

Ps. If anyone has a line on a really great code display plugin for WordPress, please drop me a line. I can’t get any to do much for me. Thanks