splice()method adds or removes items from an array.
- The original array gets changed by this method.
Theory is great, but we recommend digging deeper!
Learn Syntax of splice
array.splice(index, howmany, item1, item2...)
index, or the position in which the removal (or addition process) is supposed to begin.
Secondly, you can include an optional parameter called
howmany which specifies the number of elements to be eliminated from the array. Parameter is the
item which indicates the elements to be added to the array.
|index||Required. Defines the position to add or remove elements.
Negative values will count the position from the end of the array.
|howmany||Not required. Sets the number of items to remove.
0 means nothing will be removed.
|item1, item2...||Not required. Specifies the items to add.|
var pets = ["Cat", "Mouse", "Rat", "Cactus"]; pets.splice(2, 2, "Llama", "Horse");
splice() function is considered to be perfectly-suited for array management. The invoked method will help you change the content of arrays: you can either add new elements or remove the ones that are no longer necessary.
splice() removes or adds elements directly from or to them. However, the method also generates a list of elements that were deleted from the array. If you chose only to add items, the presented array would be empty.