In JavaScript, splice()
is a method that can be used to change the contents of an array by removing or replacing existing elements and/or adding new elements. It is a versatile method that allows you to modify arrays in-place.
Syntax:
array.splice(startIndex, deleteCount, item1, item2, ...);
Parameters:
-
startIndex
: The index at which to start changing the array. If negative, it counts from the end of the array. -
deleteCount
: The number of elements to remove from the array, starting atstartIndex
. If set to0
, no elements are removed. -
item1, item2, ...
: The elements to add to the array, starting at thestartIndex
.
Example: Here is the basic example of the Array splice() method.
Javascript
let webDvlop = [ "HTML" , "CSS" , "JS" , "Bootstrap" ];
console.log(webDvlop); // Add 'React_Native' and 'Php' after removing 'JS'. let removed = webDvlop.splice(2, 1, 'PHP' , 'React_Native' )
console.log(webDvlop); console.log(removed); // No Removing only Insertion from 2nd // index from the ending webDvlop.splice(-2, 0, 'React' )
console.log(webDvlop) |
Output
[ 'HTML', 'CSS', 'JS', 'Bootstrap' ] [ 'HTML', 'CSS', 'PHP', 'React_Native', 'Bootstrap' ] [ 'JS' ] [ 'HTML', 'CSS', 'PHP', 'React', 'React_Native', 'Bootstrap' ]