JavaScript » Array » splice

Syntax:
Array.splice(index, howMany, [element1][, ..., elementN])

The splice method is used to add and/or remove elements of an array.

The splice method is used to add and/or remove elements of an array returning an array of the elements removed. You first need to specify the index at which you wish to start removing elements, and the number to remove. (if 'howMany' is 0, you should specify at least 1 element to add).

Examples

Code:
cars = ["Mercedes", "Ford", "Chrysler", "Honda", "Volvo"]
document.write(cars.splice(1,2))
Output:
Ford,Chrysler
Explanation:

This code creates an array 'cars' and then displays two elements starting with 'cars[1]':

Code:
cars = ["Mercedes", "Ford", "Chrysler", "Honda", "Volvo"]
removed_cars = cars.splice(1, 2, "Citreon")
document.write(removed_cars + "<BR>")
document.write(cars)
Output:
Ford,Chrysler
Mercedes,Citreon,Honda,Volvo
Explanation:

You can also include optional new elements to replace the ones removed. Expanding on the previous example, this code would create an array consisting of the two extracted elements "Ford" and "Chrysler", but replace them with "Citreon" in the original array: