具型別陣列

具型別陣列是一種資料型別,它就像內建資料型別,可以加註變數、常數、函式和參數。 每個具型別陣列都有基底資料型別,陣列的每個元素都是這種基底型別。 基底型別本身可以是陣列型別,允許由陣列組成的陣列。

使用具型別陣列

在資料型別後面接一組方括弧,就能定義一維的具型別陣列。 若要定義 n 維陣列,在基底資料型別後面的這組方括弧中間,必須有 n -1 個逗號。

具型別陣列的型別變數不會一開始就配置有儲存區,而且初始值是 Undefined。 若要初始化一個陣列變數,請使用 new 運算子、陣列常值、陣列建構函式或其他陣列。 這種初始化可能發生在具型別陣列變數被宣告時或是稍後和其他型別的變數一起宣告時。 如果變數或參數的維度不符合指定給變數或傳遞給參數的陣列的維度 (或型別),就會產生型別不符合的錯誤。

您可以使用陣列建構函式來建立一個具有指定 (固定) 大小且特定原生型別的陣列。 每個引數都必須是評估為非負值整數的運算式, 而且引數的值會決定每個維度中陣列的大小,引數的數目則決定陣列的維度。

以下顯示一些簡單的陣列宣告:

// Simple array of strings; initially empty. The variable 'names' itself
// will be null until something is assigned to it
var names : String[];

// Create an array of 50 objects; the variable 'things' won't be null,
// but each element of the array will be until they are assigned values.
var things : Object[] = new Object[50];
// Put the current date and time in element 42.
things[42] = new Date();

// An array of arrays of integers; initially it is null.
var matrix : int[][];
// Initialize the array of arrays.
matrix = new (int[])[5];
// Initialize each array in the array of arrays.
for(var i = 0; i<5; i++)
   matrix[i] = new int[5];
// Put some values into the matrix.
matrix[2][3] = 6;
matrix[2][4] = 7;

// A three-dimensional array
var multidim : double[,,] = new double[5,4,3];
// Put some values into the matrix.
multidim[1,3,0] = Math.PI*5.;

請參閱

參考

var 陳述式

new 運算子

function 陳述式

概念

型別附註

其他資源

資料型別 (Visual Studio - JScript)