Creating Arrays

By Saud Rana

The Array constructor syntax has three different forms.

You can create an array using either

an array initializer (array literal) or
the Array constructor.
The array initializer (array literal) syntax is simple: a comma-separated list of values in square brackets. Here are some examples:

var myArray1 = [1,3,5,7,9]       // an array with 5 elements
var myArray2 = [5]               // an array with 1 element
var myArray3 = [true,'Hi',[7]]   // element types need not be the same!

If you call the constructor with two or more arguments, the arguments initialize the array elements. If you only supply one argument to the Array constructor, the argument initializes the length of the new array; the new array’s elements are not initialized. Finally, if you call the constructor without arguments, the new array’s length is set to zero, and its elements are not initialized. Here are examples:

var myArray4 = new Array(1,3,5,7,9)  // an array with 5 elements
var myArray5 = new Array(100)        // an empty array of length 100
var myArray6 = new Array()           // an empty array of length 0

Creating Arrays  (169 Views)
Create New Account