类型化数组

更新:2007 年 11 月

类型化数组是可以批注变量、常数、函数和参数的一种数据类型,就像内部数据类型一样。每一个类型化数组都有一个基数据类型,数组的每个元素都属于此基类型。此基类型本身可以是一种数组类型,允许用于数组的数组。

使用类型化数组

后面跟一组方括号的数据类型定义了一维的类型化数组。若要定义 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 语句

其他资源

数据类型 (JScript)