JavaScript Glossary: Array .splice() Method
Publikováno: 8.2.2019
Basics
The splice
array method changes an existing array by removing, adding and/or replacing specified elements from it. The method mutates the array and returns an array of...
Basics
The splice
array method changes an existing array by removing, adding and/or replacing specified elements from it. The method mutates the array and returns an array of all elements removed from the array. An empty array is returned if no elements are removed.
[1, 2, 3, 4, 5].splice(1, 3)
// [2, 3, 4]
https://scotch.io/embed/gist/99b27bc0f0ccec8274cdcb35fb3de047
Syntax
array.splice(startIndex, deleteCount[, item1, item2, ...])
3 Parameters
startIndex
This is the index at which the method begins making changes to the array. If the value provided is less than 0
or negative, it will start at that index from the end of the array rather than the beginning. If the value is greater than the length of the array, the value will be set to the length of the array.
deleteCount
This is the number of items to remove from the array. If the value specified is greater than the difference of array length
and the startIndex
, every element from the startIndex
to the end of the array will be deleted. If the value is 0
or less, no elements are removed from the array.
item1, item2,...
This is the value to be added to the array starting from the startIndex
. splice()
will remove elements from the array if no items
are provided.
Returns an array
This method will return an array of all elements removed from the array. If no elements are removed from the array, an empty array is returned.
const numbers = [1, 2, 4, 5];
numbers.splice(2, 0, 3);
// numbers: Array [1, 2, 3, 4, 5]
const oddNumbers = [1, 3, 5, 7, 11];
oddNumbers.splice(4, 1, 9);
// numbers: Array [1, 3, 5, 7, 9]
oddNumbers.splice(3, 1);
// numbers: Array [1, 3, 5, 9]
Splice mutates the original array and leaves only the remaining array items after the deletions or replacements.
Common Uses and Snippets
Remove an element at a particular index in an array
The .splice()
method is commonly used to remove a particular element in an array.
https://scotch.io/embed/gist/4d092c01ed1b66785c20d2283df0ab1b
Adding new elements starting from a position
The splice()
method is also used to add new elements in a given position in an array.
https://scotch.io/embed/gist/7be7a0c0626a70e17f7e8b70158fe513