JavaScript Editor Ajax toolkit     Ajax website 



Main Page

It is possible to create an array and populate it with other arrays. The base array can be either a JScript array or a typed array. JScript arrays allow more flexibility in the types of stored data, while typed arrays prevent storage of inappropriately typed data in the array.

Arrays of arrays are useful for applications in which each subarray has a different length. If each subarray has the same length, a multidimensional array may be more useful. For more information, see Multidimensional Arrays.

Typed Arrays of Arrays

In the following example, an array of arrays of strings stores pet names. Since the number of elements in each subarray is independent of the others (the number of cat names can be different from the number of dog names), an array of arrays is used instead of a multidimensional array.

В CopyCode imageCopy Code
// Create two arrays, one for cats and one for dogs.
// The first element of each array identifies the species of pet.
var cats : String[] = ["Cat","Beansprout", "Pumpkin", "Max"];
var dogs : String[] = ["Dog","Oly","Sib"];

// Create a typed array of String arrays, and initialze it.
var pets : String[][] = [cats, dogs];

// Loop over all the types of pets.
for(var i=0; i<pets.length; i++)
   // Loop over the pet names, but skip the first element of the list.
   // The first element identifies the species.
   for(var j=1; j<pets[i].length; j++)
      print(pets[i][0]+": "+pets[i][j]);

The output of this program is:

В CopyCode imageCopy Code
Cat: Beansprout
Cat: Pumpkin
Cat: Max
Dog: Oly
Dog: Sib

You can also use a typed array of type Object to store arrays.

JScript Array of Arrays

Using a JScript array as the base array provides flexibility in the types of stored subarrays. For example, the following code creates a JScript array that stores JScript arrays containing strings and integers.

В CopyCode imageCopy Code
// Declare and initialize the JScript array of arrays.
var timecard : Array;
timecard = [ ["Monday", 8],
             ["Tuesday", 8],
             ["Wednesday", 7],
             ["Thursday", 9],
             ["Friday", 8] ];
// Display the contents of timecard.
for(var i=0; i<timecard.length; i++)
   print("Worked " + timecard[i][1] + " hours on " + timecard[i][0] + ".");

The preceding example displays:

В CopyCode imageCopy Code
Worked 8 hours on Monday.
Worked 8 hours on Tuesday.
Worked 7 hours on Wednesday.
Worked 9 hours on Thursday.
Worked 8 hours on Friday.

See Also



JavaScript Editor Ajax toolkit     Ajax website


©