Availability: |
| |||||||
Property/method value type: | Array object | |||||||
JavaScript syntax: | - | myArray.splice(startPos, aCount, newElements) | ||||||
Argument list: | aCount | An optional count of items to remove | ||||||
newElements | An optional list of items to add | |||||||
startPos | An entry at which to start splicing |
The start position indicates where the splicing is to occur. If there are no other arguments, then the remainder of the array is truncated.
If there is a count argument present, only that number of items will be removed and the subsequent ones shuffled up to be adjacent to the front section of the array.
Any additional arguments are taken to be values to be inserted. They are not evaluated according to the techniques used by the Array.concat() method. If arrays are specified, they will not be flattened but will be inserted as they are.
This method operates on the array in place, therefore it modifies the original receiving array.
Specifying a count value of zero provides the functionality of an insert() method.
Specifying a count value larger than the array length does not cause an error, but instead truncates the array which behaves like a replace() method.
The method call returns an array containing the elements that were removed. This provides an alternative to the slice() method, but you should use slice() for portability since some MSIE browsers do not support the splice() method.
In Netscape 4, there are some bugs with the values that get returned by this method. The receiving array does get spliced, but the deleted items are not always properly returned.
// Create an array and test the Array.splice() method myArray = new Array("AAA", "BBB", "CCC", "DDD", "EEE"); document.write("Array<BR>") displayArrayAsTable(myArray); document.write("Array.splice() result<BR>") displayArrayAsTable(myArray.splice(3, 1, "XXX", "YYY", "ZZZ")); document.write("Array after splice<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 |
Prev | Home | Next |
Array.sort() | Up | Array.toLocaleString() |
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. |