Array splice() Method
The Array splice()
method removes/adds new elements from/to an array and returns the removed element(s) in an array. The syntax for this method is
array.splice(index,number,element1, ... elementN);
index
number
element1, .. , elementN
We consider an array named os
consisting of four elements
var os = ["Debian", "Fedora", "openSUSE", "Ubuntu"];
Applying the splice()
method, we set the first parameter as 1
for the starting index, the second parameter as 0
which will remove zero elements and the third parameter "Gentoo"
to be inserted as an element into the array
var remove = os.splice(1,0,"Gentoo");
and the new modified array os
with one element more becomes
["Debian", "Fedora", "Gentoo", "openSUSE", "Ubuntu"];
The variable remove
, which holds the removed element/elements is an empty array []
as no element is removed. Next we set the index at 2, the number of elements to be removed as 1, and do not provide the third parameter
var remove = os.splice(2,1);
One element at index 2 is removed ("Gentoo"
), and the new modified array os
with one element less becomes
["Debian", "Fedora", "openSUSE", "Ubuntu"];
The variable remove
now is an array with one element ["Gentoo"]
. Below is an example where the third element of the new array "openSUSE" (at index 2) is removed and replaced with "Gentoo"
var remove = os.splice(2,1, "Gentoo");
The variable remove
now holds an array with the element ["openSUSE"]
and the new array os
has become
["Debian", "Fedora", "Gentoo", "Ubuntu"];