Latest web development tutorials

JavaScript splice () method

Array Object Reference JavaScript Array Object

Examples

Add a new element in the array:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2,0,"Lemon","Kiwi");

fruits output:

Banana,Orange,Lemon,Kiwi,Apple,Mango

try it"

Definition and Usage

splice () method is used to insert, delete or replace the elements of the array.

NOTE: This method changes the original array!.


Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support splice ().


grammar

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

Parameter Values

参数 描述
index 必需。规定从何处添加/删除元素。
该参数是开始插入和(或)删除的数组元素的下标,必须是数字。
howmany 必需。规定应该删除多少元素。必须是数字,但可以是 "0"。
如果未规定此参数,则删除从 index 开始到原数组结尾的所有元素。
item1 , ..., itemX 可选。要添加到数组的新元素

return value

Type 描述
Array 如果从 arrayObject 中删除了元素,则返回的是含有被删除的元素的数组。

technical details

JavaScript version: 1.2


More examples

Examples

Remove the third element of the array, and add a new element in the array third position:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2,1,"Lemon","Kiwi");

fruits output:

Banana, Orange, Lemon, Kiwi, Mango

try it"

Examples

Remove from the beginning of the third position after the two elements of the array:

var fruits = [ "Banana", "Orange", "Apple", "Mango"];
fruits.splice (2,2);

fruits output:

Banana, Orange

try it"


Array Object Reference JavaScript Array Object