--- title: Array.prototype.splice() slug: Web/JavaScript/Reference/Global_Objects/Array/splice tags: - Array - JavaScript - 原型 - 参考 - 数组 - 方法 translation_of: Web/JavaScript/Reference/Global_Objects/Array/splice ---
splice()
方法通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。此方法会改变原数组。
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
start
array.length-n
);如果负数的绝对值大于数组的长度,则表示开始位置为第0位。deleteCount
{{optional_inline}}deleteCount
大于 start
之后的元素的总数,则从 start
后面的元素都将被删除(含第 start
位)。deleteCount
被省略了,或者它的值大于等于array.length - start
(也就是说,如果它大于或者等于含start
及之后的所有元素的数量),那么start
及之后所有元素都会被删除。deleteCount
是 0 或者负数,则不移除元素。这种情况下,至少应添加一个新元素。item1, item2, ...
{{optional_inline}}start
位置开始。如果不指定,则 splice()
将只删除数组元素。由被删除的元素组成的一个数组。如果只删除了一个元素,则返回只包含一个元素的数组。如果没有删除元素,则返回空数组。
如果添加进数组的元素个数不等于被删除的元素个数,数组的长度会发生相应的改变。
var myFish = ["angel", "clown", "mandarin", "sturgeon"]; var removed = myFish.splice(2, 0, "drum"); // 运算后的 myFish: ["angel", "clown", "drum", "mandarin", "sturgeon"] // 被删除的元素: [], 没有元素被删除
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; var removed = myFish.splice(2, 0, 'drum', 'guitar'); // 运算后的 myFish: ["angel", "clown", "drum", "guitar", "mandarin", "sturgeon"] // 被删除的元素: [], 没有元素被删除
var myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon']; var removed = myFish.splice(3, 1); // 运算后的 myFish: ["angel", "clown", "drum", "sturgeon"] // 被删除的元素: ["mandarin"]
var myFish = ['angel', 'clown', 'drum', 'sturgeon']; var removed = myFish.splice(2, 1, "trumpet"); // 运算后的 myFish: ["angel", "clown", "trumpet", "sturgeon"] // 被删除的元素: ["drum"]
var myFish = ['angel', 'clown', 'trumpet', 'sturgeon']; var removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue'); // 运算后的 myFish: ["parrot", "anemone", "blue", "trumpet", "sturgeon"] // 被删除的元素: ["angel", "clown"]
var myFish = ['parrot', 'anemone', 'blue', 'trumpet', 'sturgeon']; var removed = myFish.splice(myFish.length - 3, 2); // 运算后的 myFish: ["parrot", "anemone", "sturgeon"] // 被删除的元素: ["blue", "trumpet"]
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; var removed = myFish.splice(-2, 1); // 运算后的 myFish: ["angel", "clown", "sturgeon"] // 被删除的元素: ["mandarin"]
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; var removed = myFish.splice(2); // 运算后的 myFish: ["angel", "clown"] // 被删除的元素: ["mandarin", "sturgeon"]
规范 | 状态 | 备注 |
---|---|---|
{{SpecName('ES3')}} | {{Spec2('ES3')}} | Initial definition. Implemented in JavaScript 1.2. |
{{SpecName('ES5.1', '#sec-15.4.4.12', 'Array.prototype.splice')}} | {{Spec2('ES5.1')}} | |
{{SpecName('ES6', '#sec-array.prototype.splice', 'Array.prototype.splice')}} | {{Spec2('ES6')}} | |
{{SpecName('ESDraft', '#sec-array.prototype.splice', 'Array.prototype.splice')}} | {{Spec2('ESDraft')}} |
{{Compat("javascript.builtins.Array.splice")}}