JavaScript Array Object
The Array object is used to store a set of values in a single variable name.
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.
Complete Array Object Reference
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!
Defining Arrays
The Array object is used to store a set of values in a single variable name.
We define an Array object with the new keyword. The following code line
defines an Array object called myArray:
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.
Accessing Arrays
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:
Modify Values in Existing Arrays
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:
document.write(mycars[0]);
|
will result in the following output:
Learn XML with <oXygen/> XML Editor - Free Trial!
 |
|
oXygen helps you learn to define,
edit, validate and transform XML documents. Supported technologies include XML Schema,
DTD, Relax NG, XSLT, XPath, XQuery, CSS.
Understand in no time how XSLT and XQuery work by using the intuitive oXygen debugger!
Do you have any XML related questions? Get free answers from the oXygen
XML forum
and from the video
demonstrations.
Download a FREE 30-day trial today!
|
|