About arrays 171
for (j = 0; j < gridSize; j++) {
mainArr[i][j] = "[" + i + "][" + j + "]";
}
}
trace(mainArr);
This ActionScript creates a 3 x 3 array and sets the value of each array node to its index.
Then you trace the array (
mainArr).
3. Select Control > Test Movie to test the code.
You see the following display in the Output panel:
[0][0],[0][1],[0][2],[1][0],[1][1],[1][2],[2][0],[2][1],[2][2]
You can also use nested for loops to iterate through the elements of a multidimensional array,
as shown in the next example.
To use a for loop to iterate a multidimensional array:
1. Create a new Flash document, and save it as multiArray3.fla.
2. Add the following ActionScript to Frame 1 of the Timeline:
// from previous example
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);
for (j = 0; j < gridSize; j++) {
mainArr[i][j] = "[" + i + "][" + j + "]";
}
}
In this code, seen in the previous example, the outer loop iterates through each element
of
mainArray. The inner loop iterates through each nested array and outputs each
array node.
3. Add the following ActionScript to Frame 1 of the Timeline, following the code you entered
in step 2:
// iterate through elements
var outerArrayLength:Number = mainArr.length;
for (i = 0; i < outerArrayLength; i++) {
var innerArrayLength:Number = mainArr[i].length;
for (j = 0; j < innerArrayLength; j++) {
trace(mainArr[i][j]);
}
}
This ActionScript iterates through the elements of the array. You use the length property
of each array as the loop condition.