push() and pop():Array Stack Methods
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.
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var colors = new Array(); //create an array
var count = colors.push("A", "B"); //push two items
document.writeln(count); //2
count = colors.push("C"); //push another item on
document.writeln(count); //3
var item = colors.pop(); //get the last item
document.writeln(item); //"C"
document.writeln(colors.length); //2
</script>
</head>
<body>
</body>
</html>
The following code uses both push and index to add data to an array:
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var colors = ["A", "B"];
colors.push("C"); //add another item
colors[3] = "D"; //add an item
document.writeln(colors.length); //4
var item = colors.pop(); //get the last item
document.writeln(item); //"D"
</script>
</head>
<body>
</body>
</html>
Home
JavaScript Book
Essential Types
JavaScript Book
Essential Types
Array:
- The Array Type
- Array Built-in Methods
- Detecting Arrays
- Get and set array values
- Enumerating the Contents of an Array
- Array Length
- Array join() method
- Array concat()
- Array indexOf()
- Array lastIndexOf()
- Array every()
- Array filter() filters array with the given function.
- Array map()
- Array forEach()
- push() and pop():Array Stack Methods
- push(), shift():Array Queue Methods
- Array reduce()
- Array reduceRight()
- reverse():Reordering array
- Array slice()
- Array some()
- Array splice()
- Array sort()
- toString(), toLocaleString() and valueOf Array
- Array unshift()