How to push element into and pop element out of a Javascript array

Description

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.

Example

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 
        /*w  w  w  . j  av a 2s .co m*/
var item = colors.pop(); //get the last item 
console.log(item); //"D" 

The code above generates the following result.





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window