In this post you are going to learn how to create an array variable and push values into that array in JavaScript.
How to create an array in JavaScript?
It’s very simple, created a variable name and add [] (square brackets) beside to it.
for eg:
1 2 |
//define an array variable in javascript var arr = []; |
So, to add values into the array, is there any default function available in JavaScript? if yes then how to add it?
Yes, push() is the default method available in JavaScript. To add a value in the array see below example:
1 |
arr.push('myvalue'); |
the above example will add a value ‘myvalue’ into the array ‘arr’.
Do you have any JavaScript example explaining how to add values into an array and loop through the array?
Yes, here is the script:
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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
<html> <head> <title>How to Add values and loop through array in JavaScript</title> <script> //define an array variable var arr = []; //this function helps to push values into array function addArray(){ //get the value of the textbox var inputVal = document.getElementById('inp').value; //check if input value is not empty, then allow to push value if(inputVal != ''){ //using default JavaScript push() method to add the value into an array arr.push(inputVal); } } //this function helps to print the array values in a div function showArray(){ //find array length var len = arr.length; //clear the div 'showResult' document.getElementById('showResult').innerHTML = ''; //check if the length of the array is greater than 0 else alert user if(len > 0){ //for loop for(i=0; i<arr.length;i++){ document.getElementById('showResult').innerHTML += arr[i]+"<br>"; } }else{ alert("No Array Values, Please add using the above text box"); } } </script> </head> <body> <h3>How to Add values and loop through array in JavaScript - <a href="http://www.tutorialsmade.com/add-values-loop-through-array-in-javascript/"> Tutorialsmade.com</a></h3> <!-- form post method --> <form action="" method="post"> <label>Enter Value</label> <input type="text" name="inp" id="inp" /> <input type="button" value="Add to Array" onclick="addArray()" /> <br /><br /> <input type="button" value="Show Array" onclick="showArray()" /> </form> <div id="showResult"></div> </body> </html> |
Read the comments in the above script to understand step by step.
If you want to see the demo, please click the below link: