嵌套数组
可以创建一个数组,并使用其他数组填充该数组。 基数组可以是 JScript 数组或类型化数组。 JScript 数组在存储数据类型方面具有更大的灵活性;而类型化数组则防止在数组中存储类型不适当的数据。
嵌套的数组可用于在其中每一子数组具有不同长度的应用程序。 如果每个子数组都具有相同的长度,则多维数组更适用。 有关更多信息,请参见多维数组。
在下面的示例中,嵌套的字符串数组存储宠物的名字。 因为每个子数组中元素的数量与其他数组无关(猫名字的数量可能与狗名字的数量不同),所以使用嵌套的数组而不使用多维数组。
// 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]);
该程序的输出为:
Cat: Beansprout
Cat: Pumpkin
Cat: Max
Dog: Oly
Dog: Sib
也可以使用类型为 Object 的类型化数组来存储数组。
将 JScript 数组用作基数组,可在存储的子数组类型方面提供更大的灵活性。 例如,以下代码创建一个 JScript 数组,该数组存储包含字符串和整数的 JScript 数组。
// 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] + ".");
上面的示例显示:
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.