array.splice

array.splice

splice()方法通过删除现有元素和/或添加新元素来更改一个数组的内容。

var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; myFish.splice(2, 0, 'drum' // insert 'drum' at 2-index position // myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"] myFish.splice(2, 1 // remove 1 item at 2-index position (that is, "drum") // myFish is ["angel", "clown", "mandarin", "sturgeon"]

语法

array.splice(start) array.splice(start, deleteCount) array.splice(start, deleteCount, item1, item2, ...)

参数

start​指定修改的开始位置(从0计数)。如果超出了数组的长度,则从数组末尾开始添加内容;如果是负值,则表示从数组末位开始的第几位(从1计数);若只使用start参数而不使用deleteCount、item,如:array.splice(start) ,表示删除[start,end]的元素。

返回值

由被删除的元素组成的一个数组。如果只删除了一个元素,则返回只包含一个元素的数组。如果没有删除元素,则返回空数组。

描述

如果添加进数组的元素个数不等于被删除的元素个数,数组的长度会发生相应的改变。

示例

从第2位开始删除0个元素,插入“drum”

var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; var removed = myFish.splice(2, 0, 'drum' // myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"] // removed is [], no elements removed

从第3位开始删除1个元素

var myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon']; var removed = myFish.splice(3, 1 // removed is ["mandarin"] // myFish is ["angel", "clown", "drum", "sturgeon"]

从第2位开始删除1个元素,然后插入“trumpet”

var myFish = ['angel', 'clown', 'drum', 'sturgeon']; var removed = myFish.splice(2, 1, 'trumpet' // myFish is ["angel", "clown", "trumpet", "sturgeon"] // removed is ["drum"]

从第0位开始删除第2个元素,然后插入"parrot","anemone"和"blue"

var myFish = ['angel', 'clown', 'trumpet', 'sturgeon']; var removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue' // myFish is ["parrot", "anemone", "blue", "trumpet", "sturgeon"] // removed is ["angel", "clown"]

从第2位开始删除2个元素

var myFish = ['parrot', 'anemone', 'blue', 'trumpet', 'sturgeon']; var removed = myFish.splice(myFish.length - 3, 2 // myFish is ["parrot", "anemone", "sturgeon"] // removed is ["blue", "trumpet"]

从倒数第2位开始删除1个元素

var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; var removed = myFish.splice(-2, 1 // myFish is ["angel", "clown", "sturgeon"] // removed is ["mandarin"]

从第2位开始删除所有元素

var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; var removed = myFish.splice(2 // myFish is ["angel", "clown"] // removed is ["mandarin", "sturgeon"]

规范

SpecificationStatusComment
ECMAScript 3rd Edition (ECMA-262)StandardInitial definition. Implemented in JavaScript 1.2.
ECMAScript 5.1 (ECMA-262)The definition of 'Array.prototype.splice' in that specification.Standard
ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Array.prototype.splice' in that specification.Standard
ECMAScript Latest Draft (ECMA-262)The definition of 'Array.prototype.splice' in that specification.Living Standard

浏览器兼容性

FeatureChromeEdgeFirefoxInternet ExplorerOperaSafari
Basic Support1(Yes)15.5(Yes)(Yes)

FeatureAndroidChrome for AndroidEdge mobileFirefox for AndroidIE mobileOpera AndroidiOS Safari
Basic Support(Yes)(Yes)(Yes)1(Yes)(Yes)(Yes)