When you create a nested array, you are essentially creating a multidimensional array. Figure 5.18 shows a diagram of a single array and a multidimensional array, side by side.
The beauty of a multidimensional array is the indexing system it uses. By simply tacking an extra index to the end of the array, you can refer to any element of a multidimensional array. An array access on a two-dimensional array would have the following general form:
myArray[row][column];
As you can see from the general form and Figure 5.18, the first index indicates the row of the element to access, and the second index indicates the column. With that in mind, consider the following script:
myArray = new Array(); for(i=0; i<5; ++i){ myArray[i] = new Array(); for(j=0; j<5; ++j) myArray[i][j] = "["+i+","+j+"]"; } for(i=0; i<5; ++i){ myOutputString = ""; for(j=0; j<5; ++j) myOutputString += myArray[i][j] + ""; trace(myOutputString); }
This script is designed to create a two-dimensional array of strings where each string is an (x,y) pair indicating the indexes of that element. The program outputs this array in a block form so that the output matches the actual array being printed, as seen in Figure 5.19. Notice that in both loops , we are accessing the individual elements with a double index (two sets of brackets).
Arrays can have even more than two dimensions. They can, in theory, have any number of dimensions you like. Consider the following example of the three-dimensional array that is 3 — 3 — 5:
myArray = new Array(); for(i=0; i<3; ++i){ myArray[i] = new Array(); for(j=0; j<3; ++j){ myArray[i][j] = new Array(); for(k=0; k<5; ++k) myArray[i][j][k] = "("+i+","+j+","+k+")"; } } for(i=0; i<3; ++i){ for(j=0; j<3; ++j){ myOutputString = ""; for(k=0; k<5; ++k) myOutputString += myArray[i][j][k] + ""; trace(myOutputString); } trace(""); //blank line }
The output of this example can be seen in Figure 5.20. Notice the way that each index gets more local. In other words, the first index is the broadest, the second is a bit less broad, and the third is very specific. You could say the first index is the block number, the second is the row number, and the third is the column number. The only problem with that naming scheme is that you'll have to invent more names when you take arrays beyond three dimensions.
These multidimensional arrays are extremely important for us. Most board games make heavy use of them. As a result, you'll see countless examples of their use in this book. We're almost ready to get to this chapter's games , but first we need to talk about one final thing arrays can be used for in Flash.