Use Javascript array as stack

Description

Javascript array can behave like a stack.

A stack is a last-in-first-out (LIFO) structure, meaning that the most recently added item is the first one removed.

The insertion and removal of items in a stack occur at only one point: the top of the stack. For a stack the inserting is called a push, while the deleting is called a pop.

Javascript arrays provide push() and pop() specifically to allow stack-like behavior.

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 the removed item.

Example


var colors = new Array();               //create an array
var count = colors.push("A", "B");      //push two items
console.log(count);  //2
console.log(colors);/* w ww . ja v  a2  s . c  o  m*/

count = colors.push("black");           //push another item on
console.log(count);  //3
console.log(colors);

var item = colors.pop();                //get the last item
console.log(item);   
console.log(colors.length);  //2
console.log(colors);

The code above generates the following result.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions