Visit Mozilla.org

Core JavaScript 1.5 Reference:Global Objects:Array:splice

From MDC


Contents

[edit] Summary

Changes the content of an array, adding new elements while removing old elements.

Method of Array
Implemented in: JavaScript 1.2, NES 3.0

JavaScript 1.3: returns an array containing the removed elements.

ECMA Version: ECMA-262 Edition 3

[edit] Syntax

array.splice(index, howMany, [element1][, ..., elementN]);
array.splice(index, [howMany, [element1][, ..., elementN]]);  // SpiderMonkey extension

[edit] Parameters

index 
Index at which to start changing the array.
howMany 
An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed. In this case, you should specify at least one new element. If no howMany parameter is specified (second syntax above, which is a SpiderMonkey extension), all elements after index are removed.
element1, ..., elementN 
The elements to add to the array. If you don't specify any elements, splice simply removes elements from the array.

[edit] 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.

The splice method returns an array containing the removed elements. If only one element is removed, an array of one element is returned.

[edit] Backward Compatibility

[edit] 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.

[edit] Examples

[edit] Example: Using splice

The following script illustrate the use of splice:

// assumes a print function is defined
var myFish = ["angel", "clown", "mandarin", "surgeon"];
print("myFish: " + myFish);

var removed = myFish.splice(2, 0, "drum");
print("After adding 1: " + myFish);
print("removed is: " + removed);

removed = myFish.splice(3, 1);
print("After removing 1: " + myFish);
print("removed is: " + removed);

removed = myFish.splice(2, 1, "trumpet");
print("After replacing 1: " + myFish);
print("removed is: " + removed);

removed = myFish.splice(0, 2, "parrot", "anemone", "blue");
print("After replacing 2: " + myFish);
print("removed is: " + removed);

This script displays:

myFish: angel,clown,mandarin,surgeon
After adding 1: angel,clown,drum,mandarin,surgeon
removed is: 
After removing 1: angel,clown,drum,surgeon
removed is: mandarin
After replacing 1: angel,clown,trumpet,surgeon
removed is: drum
After replacing 2: parrot,anemone,blue,trumpet,surgeon
removed is: angel,clown