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.
There are some bugs in the way this works in MSIE. These are mostly to do with specifying negative values for range specifiers. These bugs are still extant as of version 5 of MSIE so you should avoid using the negative indices, and instead measure the length of the array and compute a positive index to use instead. Be careful of 'off by one' errors when you do this.
// 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 |
| Prev | Home | Next |
| Array.shift() | Up | Array.sort() |
JavaScript Programmer's Reference, Cliff Wootton Wrox Press (www.wrox.com) Join the Wrox JavaScript forum at p2p.wrox.com Please report problems to support@wrox.com © 2001 Wrox Press. All Rights Reserved. Terms and conditions. | ||