Udostępnij za pośrednictwem


Typed Arrays

A typed array is a data type that can annotate variables, constants, functions, and parameters as if it were an intrinsic data type. Every typed array has a base data type, and each element of the array is of that base type. The base type can itself be an array type, allowing for arrays of arrays.

Using Typed Arrays

A data type that is followed by a set of square brackets defines a one-dimensional typed array. To define an n-dimensional array, the base data type is followed by a set of square brackets with n-1 commas between the brackets.

No storage is initially allocated for a variable of a typed array type, and the initial value is undefined. To initialize an array variable, use the new operator, an array literal, an array constructor, or another array. The initialization can occur when the typed array variable is declared or later, as with variables of other types. A type mismatch error will result if the dimensionality of a variable or parameter does not match the dimensionality (or type) of the array assigned to the variable or passed to the parameter.

Using an array constructor, you can create an array of a given native type with a specified (fixed) size. Each argument must be an expression that evaluates to a nonnegative integer. The value of each argument determines the size of the array in each dimension; the number of arguments determines the dimensionality of the array.

The following shows some simple array declarations:

// 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.;

See Also

Reference

var Statement

new Operator

function Statement

Concepts

Type Annotation

Other Resources

Data Types (Visual Studio - JScript)