Changes

JavaScript Arrays

902 bytes added, 14:25, 15 May 2007
Initializing the Elements of an Array
== Initializing the Elements of an Array ==
 
before looking at how to add items to an array it is important to understand how arrays are index. the first item in an array is item 0, the second is item 1 and so on.
 
There are a number of different ways to initialize an array. One way is to specify the intial items at creation time by passing through the items as arguments to the the ''Array()'' constructor:
 
<pre>
 
var myColors = new Array ("Red, "Green", "Blue", "Indigo", "Violet");
 
</pre>
 
Another mechanism is to assign an item to each array element slot using an index value surrounded by [ and ]:
 
<pre>
 
var myColors = new Array();
 
myColors[0] = "Red";
myColors[1] = "Green";
myColors[2] = "Indigo";
myColors[3] = "Violet";
 
</pre>
 
Any time you need to change the value of an array elemt the same approach applies. For example to change the second elemt of the array from "Green" to "Yellow":
 
<pre>
 
muColors[1] = "Yellow";
 
</pre>