Array.unshift() (Method)

Push onto a stack whose access is FILO from the start rather than the end.

Availability:

ECMAScript edition - 3
JavaScript - 1.2
JScript - 5.5
Internet Explorer - 5.5
Netscape - 4.0
Netscape Enterprise Server - 3.0
Property/method value type:Number primitive
JavaScript syntax:-myArray.unshift(someValue, ...)
Argument list:someValueA series of values to be pushed onto the stack.

This operates very like the Array.push() method except that items are added to the front of the stack rather than the end of the stack. The items are also pushed in reverse order if several are presented at once. That is to say, the order or presentation is preserved within the array.

When the push is completed, the item at the front of the array is returned.

The number of items that were added increases the array length.

If arrays are presented, they will be pushed on as they are and not flattened. When they are subsequently removed from the stack, they will still be arrays.

This method modifies the array in place.

The result of this method is the new length of the receiving array after the pushed item has been concatenated onto its tail.

Example code:

   // Create an array and test the Array.unshift() method

   myArray = new Array("AAA", "BBB", "CCC");

   document.write("Array<BR>")

   displayArrayAsTable(myArray);

   document.write("Array.unshift()<BR>")

   document.write(myArray.unshift("XXX"))

   document.write("<BR><BR>")

   document.write("Array after unshift('XXX') call<BR>")

   displayArrayAsTable(myArray);

   

   // Display an array in a table

   function displayArrayAsTable(anArray)

   {

      myLength = anArray.length;

      document.write("<TABLE BORDER=1>");

      for(myIndex = 0; myIndex < myLength; myIndex++)

      {

         document.write("<TR><TD>");

         document.write(myIndex);

         document.write("</TD><TD>");

         document.write(anArray[myIndex]);

         document.write("</TD></TR>");

      }

      document.write("</TABLE><BR><BR>")

   }

See also:Array.prototype, Array.push(), Array.shift(), Queue manipulation, Stack manipulation

insert figure 0108

Cross-references:

ECMA 262 edition 3 - section - 15.4.4.13