Javascript provides us with built in Array objects that have methods and properties. Arrays in Javascript are dynamic and very easy to work with. You can insert, pop, shift, unshift, and iterate over array elements using the provided array methods.
In this post, I want to discuss a very good method called splice()
, that is able to do two things (inserting and removing) elements into and from an array.
Array.prototype.slice()
This method has a special syntax, where the parameters passed to it vary based on the operation it is intended to do. If you have an array called items:
var items = ['pen', 'paper', 'pencil', 'book'];
items.splice(startingIndex, numberOfElementsToDelete, item1, item2, item3....);
startingIndex
is the index at which the element is inserted at OR the index at which the element you want to remove is placed.
numberOfElementsToDelete
is the number of elements you intend to delete, starting at the startingIndex. If you are doing an insert, 0 should be passed as this parameter.
item1, item2, item3 ....
these are the items you intend to insert into the array starting at the 'startingIndex'.
Example of Insert operation:
var items = ['pen', 'paper', 'pencil', 'book'];
items.splice(2, 0, 'Marker', 'Backpack');
The above invocation of splice should modify the items array into the following:
["pen", "paper", "Marker", "Backpack", "pencil", "book"]
We passed 0 as the second parameter since we are not deleting and passed multiple elements to be inserted.
Example of a delete operation:
var items = ['pen', 'paper', 'pencil', 'book'];
items.splice(2, 2);
The second parameter in the invocation of the splice method above has the value 2. That means, we want to remove 2 elements
starting from the index 2 (the first parameter).
The above invocation of splice should modify the items array into the following:
["pen", "paper",]
Remember, there are third and fourth parameters in the above, as our objective was deleting and not inserting elements.
I am starting to just scratch the surface with these techniques!!!! Thanks for the info-
I followed you :)))))
Thanks @monerolisk. I followed you as well :)
This post recieved an upvote from minnowpond. If you would like to recieve upvotes from minnowpond on all your posts, simply FOLLOW @minnowpond
This post recieved an upvote from minnowpond. If you would like to recieve upvotes from minnowpond on all your posts, simply FOLLOW @minnowpond
Congratulations @codero! You have completed some achievement on Steemit and have been rewarded with new badge(s) :
Award for the number of comments
Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here
If you no longer want to receive notifications, reply to this comment with the word
STOP