11.11 Multidimensional Arrays

ActionScript for Flash MX: The Definitive Guide, 2nd Edition
By Colin Moock
Chapter 11.  Arrays

So far, we've limited our discussion to one-dimensional arrays, which are akin to a single row or a single column in a spreadsheet. But what if we want to create the equivalent of a spreadsheet with both rows and columns? We need a second dimension. ActionScript natively supports only one-dimensional arrays, but we can simulate a multidimensional array by creating arrays within arrays. That is, we can create an array that contains elements that are themselves arrays (sometimes called nested arrays).

The simplest type of multidimensional array is a two-dimensional array, in which elements are organized conceptually into a grid of rows and columns the rows are the first dimension of the array, and the columns are the second.

Using a practical example, let's consider how a two-dimensional array works. Suppose we're processing an order that contains three products, each with a quantity and a price. We want to simulate a spreadsheet with three rows (one for each product) and two columns (one for the quantity and one for the price). We create a separate array for each row, with each row's elements representing the values in each column:

var row1 = [6, 2.99];   // Quantity 6, Price 2.99 var row2 = [4, 9.99];   // Quantity 4, Price 9.99 var row3 = [1, 59.99];  // Quantity 1, Price 59.99

Next, we place the rows into a container array named spreadsheet:

var spreadsheet = [row1, row2, row3];

Now we can find the total cost of the order by multiplying the quantity and price of each row and adding them all together. We access a two-dimensional array's elements using two indexes (one for the row and one for the column). The expression spreadsheet[0], for example, represents the first row's two-column array. Hence, to access the second column in the first row of spreadsheet, we use spreadsheet[0][1]:

// Create a variable to store the total cost of the order. var total; // Now find the cost of the order. For each row, multiply the columns // together, and add that to the total. for (var i = 0; i < spreadsheet.length; i++) {   total += spreadsheet[i][0] * spreadsheet[i][1]; } trace(total);  // Displays: 117.89

Aside from storage and access, multidimensional arrays behave just like normal arrays. We can use all of the Array methods to manipulate data stored in multidimensional arrays.

     



    ActionScript for Flash MX. The Definitive Guide
    ActionScript for Flash MX: The Definitive Guide, Second Edition
    ISBN: 059600396X
    EAN: 2147483647
    Year: 2002
    Pages: 780
    Authors: Colin Moock

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