The splice() method can add items to an array.
The splice() method can add items to an array.
The splice() method can also removes items from an array, and returns the removed item(s).
This method changes the original array.
array.splice(index,how_many,item1, .....,itemX)
Parameter | Require | Description |
---|---|---|
index | Required. | An integer that specifies at what position to add/remove items, Use negative values to specify the position from the end of the array |
how_many | Optional. | The number of items to be removed. If set to 0, no items will be removed |
item1, ..., itemX | Optional. | The new item(s) to be added to the array |
A new Array, containing the removed items (if any)
Add items to the array:
var myArray = ["XML", "Json", "Database", "Mango"]; console.log( myArray );/*w w w .j ava 2 s. com*/ myArray.splice(2, 0, "Lemon", "Kiwi"); console.log( myArray ); //At position 2, add the new items, and remove 1 item: var myArray = ["XML", "Json", "Database", "Mango"]; console.log( myArray ); myArray.splice(2, 1, "Lemon", "Kiwi"); console.log( myArray ); //At position 2, remove 2 items: var myArray = ["XML", "Json", "Database", "Mango", "Kiwi"]; console.log( myArray ); myArray.splice(2, 2); console.log( myArray );