Apr
26
2008

Different ways of creating an Array

There are number of ways of creating an array, depending on how you are going to use it in your project...

The shortest way to create an Array:

//shorthand:
var testArray:Array = [];

//standard:
var testArray:Array = new Array();

 

Below creates an empty array with specified number of "places":

var testArray:Array = new Array(5);

trace(testArray); //returns ",,,," (empty elements)
trace(testArray.length); //returns 5

 

Below creates an array with one String element:

var testArray:Array = new Array("5");

trace(testArray); //traces 5
trace(testArray.length); //traces 1

 

Below the array literal notation:

var testArray:Array = [10, 20, 30];

trace(testArray); //traces 10,20,30
trace(testArray.length); //traces 3

And the same notation used to create an array holding different type of objects:

var testArray:Array = [1, true, "hello", new MovieClip(), 
function
(){trace("Hello, this is inline function")}];


//below traces 1,true,hello,[object MovieClip],function Function() {}
trace(testArray);
trace(testArray.length); //traces 5

testArray[4](); //runs function that traces "Hello, this is inline function"

AS3 Tips

I'm with Adobe - Facebook group