--- title: Array.prototype.splice() slug: Web/JavaScript/Reference/Global_Objects/Array/splice tags: - Array - JavaScript - Method - Prototype - Reference translation_of: Web/JavaScript/Reference/Global_Objects/Array/splice ---
splice()
方法可以藉由刪除既有元素並/或加入新元素來改變一個陣列的內容。
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
start
deleteCount
{{optional_inline}}deleteCount
,或假如其值大於 array.length - start
(也就是 deleteCount
大於 start
算起的剩餘元素數量),則所有從 start
開始到陣列中最後一個元素都會被刪除。deleteCount
為 0 或是負數,則不會有元素被刪除。 因此,你應該給定至少一個欲加入的新元素(見下方說明)。item1, item2, ...
{{optional_inline}}start
開始,要加入到陣列的元素。 如果你沒有指定任何元素,則 splice()
只會依照 start
和 deleteCount
刪除陣列的元素。一個包含被刪除的元素陣列。如果只有一個元素被刪除,依舊是回傳包含一個元素的陣列。 倘若沒有元素被刪除,則會回傳空陣列。
如果你插入的元素數量和刪除的數量不同,則回傳的陣列長度也會和原先的不同。
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; var removed = myFish.splice(2, 0, 'drum'); // myFish 為 ["angel", "clown", "drum", "mandarin", "sturgeon"] // removed 為 [], 沒有元素被刪除
var myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon']; var removed = myFish.splice(3, 1); // removed 為 ["mandarin"] // myFish 為 ["angel", "clown", "drum", "sturgeon"]
var myFish = ['angel', 'clown', 'drum', 'sturgeon']; var removed = myFish.splice(2, 1, 'trumpet'); // myFish 為 ["angel", "clown", "trumpet", "sturgeon"] // removed 為 ["drum"]
var myFish = ['angel', 'clown', 'trumpet', 'sturgeon']; var removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue'); // myFish 為 ["parrot", "anemone", "blue", "trumpet", "sturgeon"] // removed 為 ["angel", "clown"]
var myFish = ['parrot', 'anemone', 'blue', 'trumpet', 'sturgeon']; var removed = myFish.splice(myFish.length - 3, 2); // myFish 為 ["parrot", "anemone", "sturgeon"] // removed 為 ["blue", "trumpet"]
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; var removed = myFish.splice(-2, 1); // myFish 為 ["angel", "clown", "sturgeon"] // removed 為 ["mandarin"]
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; var removed = myFish.splice(2); // myFish 為 ["angel", "clown"] // removed 為 ["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")}}