Create an Array
An array can be defined in three ways.
The following code creates an Array object called myCars:
Listing 1:
1 2 3 4 | var myCars= new Array();
myCars[0]= "Saab" ;
myCars[1]= "Volvo" ;
myCars[2]= "BMW" ;
|
Listing 2:
1 | var myCars= new Array( "Saab" , "Volvo" , "BMW" );
|
Listing 3:
1 | var myCars=[ "Saab" , "Volvo" , "BMW" ];
|
Note: If you specify numbers or true/false values inside the array then the variable type will be Number or Boolean, instead of String.
Access an Array
You can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0.
The following code line:
1 | document.write(myCars[0]);
|
will result in the following output:
Modify Values in an Array
To modify a value in an existing array, just add a new value to the array with a specified index number:
Now, the following code line:
1 | document.write(myCars[0]);
|
will result in the following output: