Creating jagged arrays in Actionscript
2 March 2010
No Comments
First things first, what’s a jagged array?
A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an “array of arrays.”
Recently I’ve been playing with FLARTooKit and I found this function into the class ArrayUtils.as.
public function createJaggedArray(len:int, ...args):Array { var arr:Array = new Array(len); while (len--) { arr[len] = args.length ? createJaggedArray.apply(null, args) : 0; } return arr; }
The function made me smile due to his simplicity. 5 lines of code, use of the … (rest) parameter and a bit of recursion and you have it, a useful function to create arrays with as many dimensions as you want.
So, do you want a 3 x 5 x 2 array? Just call the function as follows:
var jaggedArray:Array = createJaggedArray(3,5,2);
Have your say