The Array object is used to store multiple values in a single variable.
|
Try it Yourself - Examples |
Create an
array
Create an array, assign values to it, and write the values to the
output.
For...In
Statement
How to use a for...in statement to loop through the elements of
an array.
Join
two arrays - concat()
How to use the concat() method to join two
arrays.
Put array
elements into a string - join()
How to use the join() method to put all
the elements of an array into a string.
Literal
array - sort()
How to use the sort() method to sort a literal array.
Numeric
array - sort()
How to use the sort() method to sort a numeric array.
For a complete reference of all the properties and methods that can be used with the Array object, go to our complete Array object reference.
The reference contains a brief description and examples of use for each property and method!
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:
cars1="Saab"; cars2="Volvo"; cars3="BMW"; |
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?
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.
The following code creates an Array object called myCars:
var myCars=new Array(); |
There are two ways of adding values to an array (you can add as many values as you need to define as many variables you require).
1:
var myCars=new
Array(); myCars[0]="Saab"; myCars[1]="Volvo"; myCars[2]="BMW"; |
You could also pass an integer argument to control the array's size:
var myCars=new
Array(3); myCars[0]="Saab"; myCars[1]="Volvo"; myCars[2]="BMW"; |
2:
var myCars=new Array("Saab","Volvo","BMW"); |
Note: If you specify numbers or true/false values inside the array then the type of variables will be numeric or Boolean instead of string.
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]); |
will result in the following output:
Saab |
To modify a value in an existing array, just add a new value to the array with a specified index number:
myCars[0]="Opel"; |
Now, the following code line:
document.write(myCars[0]); |
will result in the following output:
Opel |
Copyright © 2011 - All Rights Reserved - Softron.in
Template by Softron Technology