陣列的陣列

您可以用其他陣列來建立陣列並填入。 基底陣列可為 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 陣列,且其儲存了含有字串和整數的 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.

請參閱

概念

陣列資料

多維陣列 (Visual Studio - JScript)

其他資源

JScript 陣列