What is an Array?
An array is a special variable, which can hold more than one value, at a time.If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
var
car1="Saab";
var car2="Volvo";
var car3="BMW";
var car2="Volvo";
var car3="BMW";
The best solution here is to use an array!
An array can hold all your variable values under a single name. And you can access the values by referring to the array name.
Each element in the array has its own ID so that it can be easily accessed.
Create an Array
An array can be defined in three ways.The following code creates an Array object called myCars:
1:
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";
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 array
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:
document.write(myCars[0]);
Saab
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:
myCars[0]="Opel";
document.write(myCars[0]);
Opel
No comments:
Post a Comment