let sports = [ "football" , "basketball" , "swimming", "cricket"]
Whenever we initialize any variable as an array, then that array variable holds many methods for its manipulation.
There are almost four methods which you can use to transform the array :
.push( )
adds items to the end of the array..pop()
delete an item from the last index of the array..shift()
delete the item from first index..unshift
Add the new item at the beginning.
When I was learning array, recalling these methods was very tough and I always use to google out for the them.
But there is a single function which can perform all the 4 functions mentioned above.
.splice()
can perform insertion, deletion, replacement.
Syntax
arr.splice( startIndex , deleteCount , elem* , elem* )
sports.splice ( 1 , 2,"running" )
The syntax looks complicated but let's see what each of these argument means
startIndex - The index of the element from where you want to modify the array.
deleteCount - The no of the element you want to delete from
startIndex
includingstartIndex too.
Example :
sports.split(1, 2)
so the deletion count from basketball
which is at 1
index (startIndex) to swimming
(2 index).
- elem - You can also add many elements to the array from startIndex and it is optional.
for example :
If you want to add element but without any deletion of element from the array.
You can set deleteCount
to 0
and all element will be added to the array.
You'll notice that the element basketball
which was previously at index 1 pushed back to another index after all the element added.
So .splice
is doing all that for you in one line of function.
- As we already know,
.push( )
adds items to the end of the array.
So lets perform .push( )
using splice( )
.pop( )
usingsplice( )
.shift( )
delete the element from the first index , lets usesplice( )
for the same.
- To add the element at the beginning we use
.unshift( )
but this can also be done by.splice( )
.
So the .splice( )
can perform all the operations and it is very pretty easy to remember.
meanwhile .splice( )
Thank you :)