Friday, February 29, 2008

Flexible Arrays in AS3

posted by John Blanco @ 10:33 AM


Yeah, so for years I've been coding in AS1 and now I'm finally free. FREE! FREE! So now I'm doing AS3, and I'm very comfy with it, but like every day I find new stuff AS3 does to make my life easier.

So here's a lesson on AS3 Array methods.

Arrays in AS3 are a lot more powerful than they used to be, though many Actionscript programmers like myself haven't caught up yet. Well, here ya go.

How To Use These Methods

All of these methods have a similar signature. Specifically, the argument callback, which is a function that takes the following arguments:

  • element:* - the element of the array
  • index:int - the index of the element of the array
  • arr:Array - the array

Real simple. I summarize it here because, when I was looking at the docs, for whatever reason, it seemed intimidating. :-) If you want an idiom for remembering the order of the arguments so you can be one of those cool I-don't-need-no-docs programmers, I use the phrase Effectively Iterating Arrays. If you think that's lame then go find your own way to remember it and leave me alone.


This method checks to see if every element of the array is satisfied by a certain condition. You can use this method to check for the absence of nulls, negative numbers, or some other condition.

Some examples:

var myArray:Array = ["Jose", "Luis", "Carlos", "David", null, "Moises"];

// are all the names non-null?
var allPlayersValid:Boolean = myArray.every(function(e:*, i:int, a:Array) { return (e != null) });

var myArray:Array = [-5, 0, 5, 10, 15];

// are all the value positive?
var allPositive:Boolean = myArray.every(function(e:*, i:int, a:Array) { return (e >= 0) });

var myArray:Array = [-5, 0, 5, 10, 15];

// are all the values multiples of 5?
var allFactor5:Boolean = myArray.every(function(e:*, i:int, a:Array) { return (e % 5 == 0) });


This one is neat. It runs a function on every item of your array and returns you a new array with all the results. So, you can use this to run text conversions and that sort of thing.

Some examples:

var myArray:Array = ["Silvio", "tony", "MEADOW", "PAulie", "christopher"];

// correct captialization on all names
var newArray:Array =*, i:int, a:Array) { return e.charAt(0).toUpperCase + e.slice(1).toLowerCase(); });


Need to find some element that matches some criteria? This method does that. So, say I want to find out if any of the array elements matches the actual number of jellybeans in the jar:

var guesses:Array = [4234, 354345, 2342, 345643, 34634, 3452342, ...];

// did anyone guess right?
var weHaveAWinner:Boolean = myArray.some(function(e:*, i:int, a:Array) { return e == WINNING_JELLYBEAN_COUNT; });

But don't ask who did win. This method only returns a boolean result. :-)


Post a Comment

<< Home