170 Syntax and Language Fundamentals
To create a basic multidimensional array and retrieve elements from the array:
1. Create a new Flash document, and save it as multiArray1.fla.
2. Add the following ActionScript to Frame 1 of the Timeline:
var twoDArray:Array = new Array(new Array("one","two"), new
Array("three", "four"));
trace(twoDArray);
This array, twoDArray, consists of two array elements. These elements are themselves
arrays consisting of two elements. In this case,
twoDArray is the main array that contains
two nested arrays.
3. Select Control > Test Movie to test the code. You see the following display in the
Output panel.
one,two,three,four
4.
Return to the authoring tool and open the Actions panel. Comment out the trace
statement, as shown below:
// trace(twoDArray);
5.
Add the following ActionScript at the end of your code on Frame 1 of the Timeline:
trace(twoDArray[0][0]); // one
trace(twoDArray[1][1]); // four
To retrieve elements of a multidimensional array, you use multiple array access ([])
operators after the name of the top-level array. The first
[] refers to the index of the top-
level array. Subsequent array access operators refer to elements of nested arrays.
6. Select Control > Test Movie to test the code. You see the following display in the
Output panel.
one
four
You can use nested for loops to create multidimensional arrays. The next example shows
you how.
To create a multidimensional array using a for loop:
1. Create a new Flash document, and save it as multiArray2.fla.
2. Add the following ActionScript to Frame 1 of the Timeline:
var gridSize:Number = 3;
var mainArr:Array = new Array(gridSize);
var i:Number;
var j:Number;
for (i = 0; i < gridSize; i++) {
mainArr[i] = new Array(gridSize);