Array literals
An array can be defined in three ways.
The following code creates an Array object called myCars:Note: If you specify numbers or true/false values inside the array then the variable type will be Number or Boolean, instead of String.
var myCars=new Array(); // regular array (add an optional integer myCars[0]="Saab"; // argument to control array's size) myCars[1]="Volvo"; myCars[2]="BMW";
var myCars=new Array("Saab","Volvo","BMW"); // condensed array
var myCars=["Saab","Volvo","BMW"]; // literal arrayOk, moving on, lets explain the kind of values literal notation supports. Apart from the obvious "string" and "numeric" input, you can also use expressions:
If you can't make up your mind what to enter, undefined values are accepted too, by using a comma (,) in place of the value:
var myarray=[x+y, 2, Math.round(z)]In the above, there are actually 6 array values, except the ones in the center are all undefined. This is useful, for example, if you wish to come back later to dynamically fill in these values, or set up your array for future expansion.
var myarray=[0,,,,5]Creating multi-dimensional arrays using literal notation
The thing about defining multi-dimensional arrays using the standard syntax is that we're often the ones taken into the next dimension before the process is over. Or is it just me? At any rate, literal notation simplifies things for everyone, as it supports nesting of other literal notation. This makes defining multi-dimensional arrays extremely easy and intuitive. The following example uses literal notation to define a array with 3 elements, the 1st element being a 2 dimensional array:
Yes, it's that easy. By merely using another literal notation as one of the array values, we add a 2nd dimension to that particular element. Let's go to "LA" shall we:
var myarray=[["New York", "LA", "Las Vegas"], Europe, Japan]Just to demonstrate literal notation's versatility in this respect, here's an array with its 1st element in turn being a 3 dimensional array:
myarray[0][1] //returns "LA"Just remember, the more brackets you use, the deeper the hole you dig!
var myarray=[[[2,4,6]], Europe, Japan]