How to use array shift method

Description

JavaScript array can act as a queue. Queues restrict access in a first-in-first-out (FIFO) data structure. A queue adds items to the end of a list and retrieves items from the front of the list.

The array method for retrieving from a queue is called shift(). shift() removes the first item in the array and returns it decreases the length of the array by one.

Example


var colors = new Array(); //create an array 
var count = colors.push("A", "B"); //push two items 
console.log(count); //2 
count = colors.push("C"); //push another item on 
console.log(count); //3 
        //w w  w  . j a  v  a  2 s.  c  om
var item = colors.shift(); //get the first item 
console.log(item); //"A" 
console.log(colors.length); //2 

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