Nested Arrays


What happens if you create an array and then populate each of its elements with other arrays? You would get a nested array. Consider the following example:

 myArray = new Array(); for(i=0; i<3; ++i){     myArray[i] = new Array();     for(j=0; j<4; ++j){         myArray[i].push("i"+i+" j"+j);     } } trace(myArray.join(": ")); 

This example has some subtle things going on, so let's take a close look at it. First, a new array is created. Then a for loop is iterated, in which the first three elements of myArray are given new nested arrays. Another nested for loop is run, which creates four new elements in the nested array. The for loop then closes and another for loop is run. This final loop calls join , which prints the main array using a colon (:) as a separator. This has the effect of printing each nested array, separated by a colon . Because each element in the array is actually an array, Flash calls toString on each of the nested arrays. You end up with output like Figure 5.17. Notice how each nested array has its elements printed with comma separators but the main array has colons? That's because we used join and not toString on our main array.

click to expand
Figure 5.17: Nested arrays are powerful tools. Here, join is called to print a set of nested arrays.



Macromedia Flash MX 2004 Game Programming
Macromedia Flash MX 2004 Game Programming (Premier Press Game Development)
ISBN: 1592000363
EAN: 2147483647
Year: 2004
Pages: 161

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net