Multidimensional arrays can be thought of as matrices, or grids. A chess board is a grid of 8 columns and rows. In programming, multidimensional arrays can be used to model these types of structures.

Creating multidimensional arrays

In ActionScript, as in JavaScript, arrays are implemented as arrays of arrays, or "nested" arrays. A chess board, for example, can be modeled as an array containing eight array elements each of which is also an array containing eight elements.

The following array, twoD_Array, consists of two array elements that are themselves arrays consisting of two elements:

twoD_Array = new Array(new Array("one","two"), new Array("three", "four"));

In this case, twoD_Array is the "main" array containing two nested arrays.

Nested for loops can be used to quickly create multidimensional arrays. For example, the following script creates a 5 x 5 array and sets the value of each array node to its index:

mainArray = new Array(5); for(i=0; i<5; i++) {  mainArray[i] = new Array(5);  for(j=0; j<5; j++) {   mainArray[i][j] = "[" + i + "][" + j + "]";  } }

Retrieving array elements

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 []'s refer to elements of nested arrays. Using twoD_Array as an example:

twoD_Array[0][0] // returns "one" twoD_Array[1][1] // returns "four"

Nested for loops can be used to iterate through the elements of a multidimensional array. In the following example, the outer loop loops through each element of mainArray. The inner loop iterates through each nested array and outputs each array node. The length property of each array is used as the loop condition:

outerArraylength = mainArray.length; for(i=0; i < outerArraylength; i++) { innerArrayLength = mainArray[i].length;  for(j=0; j < innerArraylength; j++){   trace(mainArray[i][j]);  } }

Additional Information

More information on using arrays and the Array object can be found in the Flash ActionScript Reference guide. Since ActionScript is based on JavaScript, the JavaScript Reference from Mozilla Developer Network also contains information helpful for learning ActionScript.

Keywords: loops; multi-dimensional; tn_15144

This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License  Twitter™ and Facebook posts are not covered under the terms of Creative Commons.

Legal Notices   |   Online Privacy Policy