Summary
Changes the content of an array, adding new elements while removing old elements.
Method of Array instances |
|
|---|---|
| Implemented in | JavaScript 1.2 |
| ECMAScript Edition | ECMAScript 3rd Edition |
Syntax
array.splice(index , howMany[, element1[, ...[, elementN]]])array.splice(index[, howMany[, element1[, ...[, elementN]]]])
Parameters
-
index - Index at which to start changing the array. If negative, will begin that many elements from the end.
-
howMany -
An integer indicating the number of old array elements to remove. If
howManyis 0, no elements are removed. In this case, you should specify at least one new element. If nohowManyparameter is specified (second syntax above, which is a SpiderMonkey extension), all elements afterindexare removed.
-
element1, ..., elementN -
The elements to add to the array. If you don't specify any elements,
splicesimply removes elements from the array.
Returns
An array containing the removed elements. If only one element is removed, an array of one element is returned.
Description
If you specify a different number of elements to insert than the number you're removing, the array will have a different length at the end of the call.
Backward Compatibility
JavaScript 1.2
The splice method returns the element removed, if only one element is removed (howMany parameter is 1); otherwise, the method returns an array containing the removed elements. Note that the last browser to use JavaScript 1.2 was Netscape Navigator 4, so you can depend on splice always returning an array.
Examples
Example: Using splice
The following script illustrate the use of splice:
var myFish = ["angel", "clown", "mandarin", "surgeon"]; //removes 0 elements from index 2, and inserts "drum" var removed = myFish.splice(2, 0, "drum"); //myFish is ["angel", "clown", "drum", "mandarin", "surgeon"] //removed is [], no elements removed //removes 1 element from index 3 removed = myFish.splice(3, 1); //myFish is ["angel", "clown", "drum", "surgeon"] //removed is ["mandarin"] //removes 1 element from index 2, and inserts "trumpet" removed = myFish.splice(2, 1, "trumpet"); //myFish is ["angel", "clown", "trumpet", "surgeon"] //removed is ["drum"] //removes 2 elements from index 0, and inserts "parrot", "anemone" and "blue" removed = myFish.splice(0, 2, "parrot", "anemone", "blue"); //myFish is ["parrot", "anemone", "blue", "trumpet", "surgeon"] //removed is ["angel", "clown"]
Mozilla Developer Network