Use Javascript array as queue

Description

Queues restrict access in a first-in-first-out (FIFO) data structure.

A queue adds items to the end and retrieves items from the front.

shift() from array removes the first item in the array and returns it, decrementing the length of the array by one. push() method adds items to the end of an array.

We can use shift() and push() to treat arrays as queues.

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  w w .  j  av a  2  s. co  m

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

var item = colors.shift();              //get the first item
console.log(item);                            
console.log(colors.length);  //2
console.log(colors);

The code above generates the following result.

Reversed queue

unshift() adds any number of items to the front of an array and returns the new array length.

Combining unshift() and pop(), we can use array as reversed queue , where new values are added to the front of the array and values are retrieved off the back.


var colors = new Array();               //create an array
var count = colors.unshift("A", "B");   
console.log(count);  //2
console.log(colors);/*from w  w  w.  j a v  a  2s  . com*/

count = colors.unshift("black");        
console.log(count);  //3
console.log(colors);

var item = colors.pop();               //get the first 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