Array.slice() (Method)

Slice out a sub-array from the receiving array.

Availability:

ECMAScript edition - 3
JavaScript - 1.2
JScript - 3.0
Internet Explorer - 4.0
Netscape - 4.0
Netscape Enterprise Server - 3.0
Property/method value type:Array object
JavaScript syntax:-myArray.slice(aRange)
Argument list:aRangeA range of array elements

This method returns the sliced out sub-array presented as a new array.

The range values indicate which part of the receiving array is to be sliced out.

A positive value in the range specifier indicates a particular cell. The first cell index is 0.

A negative value in the range specifier indicates a cell counted back from the end of the array. The last cell is index -1.

If only one value is indicated in the range specifier, then the second is assumed to be the end of the array.

The first specifier should indicate an element earlier than the second although some implementations may check and swap as necessary.

Warnings:

Example code:

   // Create an array and test the Array.slice() method
   myArray = new Array("AAA", "BBB", "CCC", "DDD", "EEE");
   document.write("Array<BR>")
   displayArrayAsTable(myArray);
   document.write("Array.slice(3)<BR>")
   displayArrayAsTable(myArray.slice(3))
   document.write("Array.slice(2,4)<BR>")
   displayArrayAsTable(myArray.slice(2,4))
   document.write("Array.slice(-1)<BR>")
   displayArrayAsTable(myArray.slice(-1))
   document.write("Array.slice(-3)<BR>")
   displayArrayAsTable(myArray.slice(-3))
   
   // 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, Off by one errors

insert figure 0106

Cross-references:

ECMA 262 edition 3 - section - 15.4.4.10