Sambungan Array JavaScript()
Contoh
Pada posisi 2, tambahkan 2 elemen:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
Di posisi 2, hapus 2 item:
const fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi"];
fruits.splice(2, 2);
Definisi dan Penggunaan
Metode splice()
menambahkan dan/atau menghapus elemen array.
Metode splice()
ini menimpa larik asli.
Sintaksis
array.splice(index, howmany, item1, ....., itemX)
Parameter
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. |
Nilai Kembali
Array yang berisi item yang dihapus (jika ada). |
Lebih Banyak Contoh
Di posisi 2, tambahkan item baru, dan hapus 1 item:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 1, "Lemon", "Kiwi");
Dukungan Peramban
splice()
adalah fitur ECMAScript1 (ES1).
ES1 (JavaScript 1997) didukung penuh di semua browser:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |