Javascript Array Tutorial - Adding more items
Array can grow dynamically. Let us say you have delared an array as
var x = ['toyota','honda','Audi'];
Now you wish to add more elements to this array.
You can add the next element using a simple statement like
x[3] = 'Ford';
Notice that the array indexing starts from 0. So we have
x[0] = 'toyota'; x[1] = 'honda'; x[2] = 'Audi';
Basically the last element if the array has an index one less than its length. We can use the array length to add a new element at the end of the array. So the statement
x[3] = 'Ford';
could be better written as
x[x.length] = 'Ford';
Here is the complete example
<html> <body> <script type="text/javascript"> var x = ['toyota','honda','Audi']; x[x.length] = 'Ford'; for (i=0; i<=3; i++) document.writeln('x['+i+'] = '+ x[i]+ '<br />'); </script> </body> </html> |
You may like to try this example online here .
It gives the following output
x[0] = toyota x[1] = honda x[2] = Audi x[3] = Ford
There is special function for adding an element in the array in the end - the push method. We will study it in the next post.