6.9. 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 the 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 Recipe 4.10, 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:
colors = ["maroon", "beige", "blue", "gray"]; years = [1997, 2000, 1985, 1983]; makes = ["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 thefor
statement. Here, we usemakes
.length
. for (var i = 0; i < makes.length; i++) { // Outputs: // 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]); }
Another option for working with multiple ...
Get Actionscript Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.