How to Initialize a JavaScript Array
An array is an ordered set of key/value pairs. In JavaScript, the elements of an array do not have to be of the same type. Arrays can be indexed, where the keys are consecutive integers, or associative, where the keys are strings. Arrays can also contain objects, such as other arrays, as elements. You can initialize an array with the "Array" constructor.
Instructions
-
-
1
Initialize a new array without any elements using the Array constructor. Assign elements to the array as you would assign any variable. For example, type:
var myArray = new Array();
myArray[0] = 10;
myArray[1] = 20;
-
2
Initialize an array by passing values to the Array constructor. For example, type:
var myArray = new Array("Steve", "John", "Paul", "Peter");
-
-
3
Set the number of elements in an array when you initialize it by passing the number as a parameter to the Array construct. For example, type:
var myArray = new Array(2);
myArray[0] = 1;
myArray[1] = 2;
-
4
Initialize an array of arrays or objects by calling the array or object constructor for each element. For example, type:
var myArray = new Array(new Array(10, 20, 30), new Arrray(40, 50, 60));
-
1