Javascript - Array splice() Method

The splice() method can add items to an array.

Description

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.

Syntax

array.splice(index,how_many,item1, .....,itemX)

Parameter Values

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

Return

A new Array, containing the removed items (if any)

Example

Add items to the array:

Demo

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 );

Result