There are different ways to add elements to an Array. Adding arrays in JavaScript is nothing but the appending arrays, which is generally called as JavaScript array append.
push()
method adds the new elements (one or more) to the end of an array. This method modifies the old array and returns the new length array by adding the new element/elements at the end.push()
method we can add an element/elemets to the end of an array.<p>Click the button to add a new element to the array.</p> <button onclick="myFunction()">Click</button> <p id="myId"></p> <script> var a = ["India", "Pakisthan", "Bangladesh", "China"]; document.getElementById("myId").innerHTML = a; function myFunction() { a.push("SriLanka"); document.getElementById("myId").innerHTML = a; } </script>
In the above code snippet we have given Id
as "myId
"to the second <p>
element in the HTML code. There is a function myFunction() in the<script>
block which is connected to the onclick of the HTML button and array with value "["India", "Pakisthan", "Bangladesh", "China"]" to the variable a
. We need to add the element/elements to the end of an array, for that we are using push()
method in the <script>
block. Onclick of the button "Click" in the HTML code fires the function myFunction() in the <script>
block, at the same time push() method adds the new input elemet to the end of an array and returns the new length array as output.
OUTPUT
unshift()
method adds the new elements (one or more) to the beginning of an array. This method modifies the old array and returns the new length array by adding the new element/elements at the beginning.unshift()
method we can add an element/elemets to the beginning of an array.<p>Click the button to add a new element to the array.</p> <button onclick="myFunction()">Click</button> <p id="myId"></p> <script> var a = ["India", "Pakisthan", "Bangladesh", "China"]; document.getElementById("myId").innerHTML = a; function myFunction() { a.unshift("SriLanka"); document.getElementById("myId").innerHTML = a; } </script>
In the above code snippet we have given Id
as "myId
"to the second <p>
element in the HTML code. There is a function myFunction() in the<script>
block which is connected to the onclick of the HTML button and array with value "["India", "Pakisthan", "Bangladesh", "China"]" to the variable a
. We need to add the element/elements to the beginning of an array, for that we are using unshift()
method in the <script>
block. Onclick of the button "Click" in the HTML code fires the function myFunction() in the <script>
block, at the same time unshift() method adds the new input elemet to the beginning of an array and returns the new length array as output.
OUTPUT
Views: 38499 | Post Order: 155