scripts is our array object,
starting_number is the array element number (index ) from where the starting element is to be taken up,Note that the first element index is 0
length is the number of elements to be removed starting from the starting_number, If it is 0 then nothing is removed.
list1 is the name of the element to be replaced.
The replaced list can be more than the number of items to be removed. They will be added to the array. All the elements removed from scripts array will be placed in a new array t1.
Now let us try to understand how splice method works in different conditions. We will take our scripts array example, here is our array.
Replacing elements of an array using splice method
Output is here
Adding new elements without removingYes this also can be done, just make the number of elements to be removed to 0. The position where the new element to be added can be specified by starting_number. Here is the code to add two new elements after the second element.
Output is here
Adding new element at the end of the arrayWe can do this by replacing starting_number with length of the array. In the above example replace the line with splice function with this one.
Adding new element at the beginning of the arraySame way we can add elements at the staring of the array by making the starting_number to 0
Removing element by using spliceLet us remove 2nd element.
To remove 3rd element here is the code.
var t1=scripts.splice(1,2);Here we have changed the index number only, the index number of 3rd element is 2
Removing any elementIn above code we have used index number of the element to remove it from the array. Most of the time we will be knowing the element name only ( not its index position). Here we will first use indexOf function to get the position of the element and then use splice to remove it.
This article is written by plus2net.com team.