contents   index   previous   next



Creating arrays

 

Like other objects, arrays are created using the new operator and the Array constructor function. There are three possible ways to use this function to create an array. The simplest is to call the function with no parameters:

 

var a = new Array();

 

This line initializes variable a as an array with no elements. The parentheses are optional when creating a new array, if there are no arguments. If you wish to create an array of a predefined size, pass variable a the size as a parameter of the Array() function. The following line creates an array with a length of the size passed.

 

var b = new Array(31);

 

In this case, an array with length 31 is created.

 

Finally, you can pass a list of elements to the Array()function, which creates an array containing all of the parameters passed. For example:

 

var c = new Array(5, 4, 3, 2, 1, "blast off");

 

creates an array with a length of 6. c[0] is set to 5, c[1] is set to 4, and so on up to c[5], which is set to the string "blast off". Note that the first element of the array is array[0], not array[1].

 

Arrays may also be created dynamically. By referring to a variable with an index in brackets, a variable is created as or converted to an array. The array that is created is an automatic or dynamic array which is different than an instance of an Array object created as described in this section. Automatic arrays, created as described in this paragraph, are unable to use the methods and properties described below, so it is recommended that you use, in most circumstances, the new Array() constructor function to create arrays.

 


Initializers for arrays and objects