O'Reilly logo

ActionScript 3.0 Cookbook by Joey Lott, Darron Schall, Keith Peters

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Storing Complex or Multidimensional Data

Problem

You have two or more sets of related data and you want to be able to keep track of the relationships between their elements.

Solution

Use parallel arrays, an array of arrays (a multidimensional array), or an array of objects.

Discussion

You can create two or more parallel arrays in which the elements with the same index in each array are related. For example, the beginGradientFill() method, discussed in Chapter 7, uses three parallel arrays for the colors, alphas, and ratios of the values used in the gradient. In each array, the elements with the same index correspond to one another.

To create parallel arrays, populate multiple arrays such that the elements with the same index correspond to one another. When you use parallel arrays, you can easily retrieve related data, since the indexes are the same across the arrays; for example:

var colors:Array = ["maroon", "beige",    "blue",     "gray"];
var years:Array  = [1997,     2000,       1985,       1983];
var makes:Array  = ["Honda",  "Chrysler", "Mercedes", "Fiat"];
     
// Loop through the arrays. Since each array is the same 
// length, you can use the length property of any of them 
// in the for statement. Here, we use makes.length.
for (var i:int = 0; i < makes.length; i++) {
    // Displays:
    // A maroon 1997 Honda
    // A beige 2000 Chrysler
    // A blue 1985 Mercedes
    // A gray 1983 Fiat
     
    // Display the elements with corresponding indexes 
    // from the arrays.
    trace("A " + colors[i] + " " + 
                 years[i] + " " + 
                 makes[i]);
}

Warning ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required