The splice()
method is a method in JavaScript that allows you to modify an array by removing or replacing elements, or adding new elements in place. It works by specifying the index at which to start making changes, and the number of elements to remove (if any). You can also specify one or more elements to add to the array in place of the removed elements.
Here is the syntax for the splice()
method:
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
start
: The index at which to start making changes to the array.deleteCount
: The number of elements to remove from the array, starting at thestart
index. If this parameter is omitted, thesplice()
method will remove all the elements from thestart
index to the end of the array.item1, item2, ...
: The elements to add to the array, starting at thestart
index. These elements will replace the removed elements.
Here are some examples of how you can use the splice()
method:
// Remove the first element of the array
let fruits = ['apple', 'banana', 'mango', 'orange'];
fruits.splice(0, 1); // ['apple'] is removed
console.log(fruits); // ['banana', 'mango', 'orange']
// Remove the last two elements of the array
fruits = ['apple', 'banana', 'mango', 'orange'];
fruits.splice(-2); // ['mango', 'orange'] are removed
console.log(fruits); // ['apple', 'banana']
// Insert a new element at the beginning of the array
fruits = ['apple', 'banana', 'mango', 'orange'];
fruits.splice(0, 0, 'pear'); // no elements are removed
console.log(fruits); // ['pear', 'apple', 'banana', 'mango', 'orange']
// Replace the second element with two new elements
fruits = ['apple', 'banana', 'mango', 'orange'];
fruits.splice(1, 1, 'strawberry', 'kiwi'); // ['banana'] is removed
console.log(fruits); // ['apple', 'strawberry', 'kiwi', 'mango', 'orange']
It’s important to note that the splice()
method modifies the original array in place and returns an array containing the removed elements. If you don’t want to modify the original array, you can use the slice()
method instead, which returns a new array without modifying the original array.
You can find the complete JavaScript Tutorials here.
Follow us on Facebook, YouTube, Instagram, and Twitter for more exciting content and the latest updates.