We all know array is a special variable, which can hold more than one value right?. And you could have used array in server side languages such as Java, PHP, Dot Net etc., but you know you can also use array in client side script such as JavaScript.
First I will show how to define an array in JavaScript:
1 2 |
//defining an array var myarr = new Array(); |
Defining array() is more or less same like any server side programming language.
Lets see how to add values in an array()
1 2 3 |
myarr[0] = "one"; myarr[1] = "two" myarr[2] = "three"; |
Now, an array is defined and values are added, lets see how to alert these values one by one, to do that we are going to loop through the array values:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<html> <head> <script> //defining an array var myarr = new Array(); //add values to an array myarr[0] = "one"; myarr[1] = "two" myarr[2] = "three"; //now loop through the values one by one //to do that first find array length for(var i=0; i < myarr.length; i++){ //now alert the values one by one alert(myarr[i]); } </script> </head> <body> </body> </html> |
Check the above code yourself, read the comments to know how the code is working.
So now you know how the array() is working in JavaScript, but if you see I have hard coded the values in the array, then how to add the values dynamically in an array()?.
You can add the values dynamically using push() function, lets see an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<html> <head> <script> //defining an array var myarr = new Array(); //add values to an array myarr[0] = "one"; myarr[1] = "two" myarr[2] = "three"; function alertArrayValues(){ //now loop through the values one by one for(var i=0; i < myarr.length; i++){ alert(myarr[i]); } } function addAnArray(){ //create random number var randnum = Math.round(Math.random() * 100); //add the randnum to the array "myarr" myarr.push(randnum); } </script> </head> <body> <button onclick="addAnArray()">Add a Value</button> <button onclick="alertArrayValues()">Alert all the Values</button> </body> </html> |
In the above example, basically I have added two buttons and created two function addAnArray() and alertArrayValues(), when you press the addAnArray(), it will push() a value to an existing array “myarr“, when you press alertArrayValues() it will alert all the values one by one.
See the demo here: