|
| HOW TO ADD ELEMENTS TO AN ARRAY IN JAVASCRIPT
Adding one or more elements to an existing javascript array is relatively simple:
To add elements individually without specifiying index numbers, you will need to first find the next available index number. This can be achieved using the length property. The length property gives you the number of elements in an existing array. As an array's index starts at 0, the array length property will give the next available index number as in in this example:
var colors=new Array("blue", "green");
Above equivalent to:
count[0]="blue";
count[1]="green";
alert(colors); // displays blue, green
var Count=colors.length;
var Count gives 2 which are the number of elements in this array colors. Since blue is at index 0 (array indexes always start at 0) and green is at index 1, the next available index number is 2 which is the same as the array length.
Therefore to add an element to this array, we simply do:
colors[colors.length]="red";
alert(colors); // displays blue, green, red
This array is now equivalent to:
count[0]="blue";
count[1]="green";
count[2]="red";
Now Read:
|
|