It has the following syntax
array.splice(index, quantity, item1, ..., itemX) returning an array
where the parameters are defined as:
index : it is required and specifies the position at which to add or remove items. If it is negative it will calculate from the end of the array.
quantity : it is optional and specifies the number of items to be removed from the index onwards. To not remove any items, set it to 0. If it is not specified it will remove all elements after the index.
itemX : it is optional and is the items to be added to the array at the specified index.
Lets define an array
var myArray = [1,2,3,4,5]
Now lets remove all elements from index 4 onwards
myArray.splice(4)
This results in the following array
[ 1, 2, 3, 4 ]
Now let us add some elements to our array starting at index 4,
myArray.splice(4,0,5,6,7,8,9,10)
This results in the following array
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
Now lets replace elements with values 4 and 5 with 11 and 12
myArray.splice(3,2,11,12) //remove 2 elements at index 3 and add 11 and 12 at index 3
This results in the following array
[ 1, 2, 3, 11, 12, 6, 7, 8, 9, 10 ]
Now lets remove elements with values 11 and 12 from the back of the array
myArray.splice(-7,2)
This results in the following array
[ 1, 2, 3, 6, 7, 8, 9, 10 ]
Pretty cool hey, that's enough on splicing, its time for you to experiment with it. Till next time enjoy!!!
No comments:
Post a Comment