Javascript Arrays

Posted on March 6th, 2010 by Eric Rowell

Javascript arrays are very handy data structures that allow you to easily create, retrieve, and modify a list of objects, usually strings. Let’s say that you are keeping track of a list of names. A good way to store a list of names is with an array. There are two ways to initialize an array.

1
2
3
4
var names=new Array();
names[0]="Andie";
names[1]="Eric";
names[2]="Kusco";

and

5
var names=new Array("Andie","Eric","Kusco");

The first example declares names as an empty array, and then sets the first three values of this array one by one.  The second example initializes an array by sending the Array constructor the values as parameters.  Both methods work the same.

Once you have an array, you may want to retrieve it’s contents.  The first element of an array has an index of 0, the second element has an index of 1, then 2,3,4, etc.  In the code above for example, The index of “Eric” is 1.  If we want to retrieve a value from the array, we do something like this:

6
7
var value=names[1];
alert(value);

The code above will alert “Eric” because value has been set to the element in the array names which has an index of 1, which corresponds to the value of “Eric”.

To modify an element in an array, you can do something like this:

8
names[0]="Andrea";

The code above will set the element in the arrray names with the index of 0 to “Andrea”. The array list now contains “Andrea”, “Eric”, and “Kusco”.

Tags: , , , , , , , , ,

Leave a Reply