多維陣列 (Visual Studio - JScript)

您可以在 JScript 中建立多維具型別陣列。 多維陣列使用一個以上的索引來存取資料。 當指令碼宣告陣列時,它會設定每個索引的範圍。 多維陣列與陣列的陣列類似,其每個子陣列可以有不同的長度。 如需詳細資訊,請參閱陣列的陣列

討論

資料型別名稱後面會加上一組方括弧 ([]),以便指定一維陣列資料型別。 指定多維陣列資料型別的程序也是一樣的,但是在方括弧之間有一個逗號 (,)。 陣列的維度等於逗號的數目加一。 以下範例說明已定義的一維陣列與多維陣列之間的差異。

// Define a one-dimensional array of integers. No commas are used.
var oneDim : int[];
// Define a three-dimensional array of integers.
// Two commas are used to produce a three dimensional array.
var threeDim : int[,,];

在以下範例中,字元的二維陣列是用來儲存井字遊戲板的狀態。

// Declare a variable to store two-dimensional game board.
var gameboard : char[,];
// Create a three-by-three array.
gameboard = new char[3,3];
// Initialize the board.
for(var i=0; i<3; i++)
   for(var j=0; j<3; j++)
      gameboard[i,j] = " ";
// Simulate a game. 'X' goes first.
gameboard[1,1] = "X"; // center
gameboard[0,0] = "O"; // upper-left
gameboard[1,0] = "X"; // center-left
gameboard[2,2] = "O"; // lower-right
gameboard[1,2] = "X"; // center-right, 'X" wins!
// Display the board.
var str : String;
for(var i=0; i<3; i++) {
   str = "";
   for(var j=0; j<3; j++) {
      if(j!=0) str += "|";
      str += gameboard[i,j];
   }
   if(i!=0)
      print("-+-+-");
   print(str);
}

本程式的輸出為:

O| | 
-+-+-
X|X|X
-+-+-
 | |O

您可以使用型別 Object 的多維具型別陣列來儲存任何型別的資料。

請參閱

概念

陣列資料

陣列的陣列

其他資源

JScript 陣列