JavaScript Editor Ajax toolkit     Ajax website 

Main Page

An array literal can initialize an array in JScript. An array literal, which represents a JScript Array object, is represented by a comma-delimited list that is surrounded by a pair of square brackets ([]). Each element of the list can be either a valid JScript expression or empty (two consecutive commas). The index number of the first element in the array literal list is zero; each subsequent element in the list corresponds to a subsequent element in the array. A JScript Array is sparse; if an element of the array literal list is empty, the corresponding element in the JScript Array is not initialized.

Using Array Data

In this example, the variable arr is initialized to be an array with three elements.

В CopyCode imageCopy Code
var arr = [1,2,3];

You can use empty elements in the Array literal list to create a sparse array. For example, the following Array literal represents an array that defines only elements 0 and 4.

В CopyCode imageCopy Code
var arr = [1,,,,5];

An array literal can include data of any type, including other arrays. In the following array of arrays, the second subarray has both string and numeric data.

В CopyCode imageCopy Code
var cats = [ ["Names", "Beansprout", "Pumpkin", "Max"], ["Ages", 6, 5, 4] ];

Since JScript Array objects interoperate with typed arrays, array literals can initialize typed arrays as well with a few restrictions. The data in the array literal must be convertible to the data type of the typed array. An array literal cannot initialize a multidimensional typed array, but an array literal can initialize a typed array of typed arrays. A two-step process occurs when an array literal initializes a typed array. First, the array literal is converted to a typed array, which is used to initialize the typed array. As a part of the conversion, each empty element of the array literal is first interpreted as undefined, and then every element of the literal is converted to the appropriate data type for the typed array. In the following example, the same array literal is used to initialize a JScript array, an integer array, and a double array.

В CopyCode imageCopy Code
var arr = [1,,3];
var arrI : int[] = [1,,3];
var arrD : double[] = [1,,3];
print(arr);   // Displays  1,,3.
print(arrI);  // Displays  1,0,3.
print(arrD);  // Displays  1,NaN,3.

The empty element of the array literal is represented as 0 in the integer array and NaN in the double array, since undefined maps to those values.

See Also

JavaScript Editor Ajax toolkit     Ajax website