JavaScript配列splice()
例
位置2に、2つの要素を追加します。
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
位置2で、2つのアイテムを削除します。
const fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi"];
fruits.splice(2, 2);
定義と使用法
このsplice()
メソッドは、配列要素を追加および/または削除します。
このsplice()
メソッドは元の配列を上書きします。
構文
array.splice(index, howmany, item1, ....., itemX)
パラメーター
Parameter | Description |
index | Required. The position to add/remove items. Negative value defines the position from the end of the array. |
howmany | Optional. Number of items to be removed. |
item1, ..., itemX | Optional. New elements(s) to be added. |
戻り値
削除されたアイテム(存在する場合)を含む配列。 |
その他の例
位置2で、新しいアイテムを追加し、1つのアイテムを削除します。
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 1, "Lemon", "Kiwi");
ブラウザのサポート
splice()
ECMAScript1(ES1)機能です。
ES1(JavaScript 1997)は、すべてのブラウザーで完全にサポートされています。
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |