An array can act just like a stack. A stack is a last-in-first-out (LIFO) structure.
The insertion (called a push) and removal (called a pop) in a stack occur at the top of the stack. The push() method accepts any number of arguments and adds them to the end of the array returning the array's new length.
The pop()
method removes the last item
in the array, decrements the array's length, and returns
that item.
push() |
Yes | Yes | Yes | Yes | Yes |
array.push(item1, item2, ..., itemN)
item1, item2, ..., itemN
specifies the item(s) to add to the array.
The new array length is returned from push() function.
The following code uses both push and index to add data to an array:
var colors = ["A", "B"];
colors.push("C"); //add another item
colors[3] = "D"; //add an item
console.log(colors.length); //4
var item = colors.pop(); //get the last item
console.log(item); //"D"
The code above generates the following result.
The following code shows how to add more than one item to an array.
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">push</button>
<p id="demo"></p>
<script>
var array1 = ["B", "A", "C", "M"];
document.getElementById("demo").innerHTML = array1;
<!--from w w w .j av a 2s .c o m-->
function myFunction() {
array1.push("X", "Y", "X");
document.getElementById("demo").innerHTML = array1;
}
</script>
</body>
</html>
The code above is rendered as follows: