There are several ways to add elements to an Array. The easiest way to add a new element to an array is by using the push() method:
declare variable = ["Banana", "Orange", "Apple", "Mango"];
variable-name.push("Lemon"); <== adds a new element (Lemon) to array
Another way to add elements to an array is to use the length property, which provides an easy way to append new elements to an array without using the push() method. Here is how to do that:
declare variable = ["Banana", "Orange", "Apple", "Mango", "Lemon"];
variable-name[variable-name.length] = "Watermelon"; <== adds a new element (Watermelon) to array
HTML file: | Displayed by browser: |
---|---|
<body>
<!--ORIGINAL ARRAY--> <h4>The original array:</h4> <p id="demo"></p> <hr /> <!--ADD LEMONS WITH PUSH--> <h4>The push method appends a new element to an array:</h4> <button onclick="myPush()">Push me</button> <p id="push"></p> <hr /> <!--ADD WATERMELON WITH LENGTH--> <h4>Using the length property to add an element to an array:</h4> <button onclick="myLength()">Add to Length</button> <p id="length"></p> <script> var fruits = [ "Banana", "Orange", "Apple", "Mango" ]; document.getElementById("demo").innerHTML = fruits; /*ADD LEMONS WITH PUSH*/ function myPush() { fruits.push("Lemon") document.getElementById("push").innerHTML = fruits; } /*ADD WATERMELON WITH LENGTH*/ function myLength() { fruits[fruits.length] = "Watermelon"; document.getElementById("length").innerHTML = fruits; } </script> </body> |
The original array:The push method appends a new element to an array:Using the length property to add an element to an array: |