The syntax of the splice() method is as follows:
array.splice(start, deleteCount, item1, item2, ...)
array: The array you want to modify.
You can use the splice() method to remove elements from an array. Here's an example:
const fruits = ['apple', 'banana', 'cherry', 'date'];
fruits.splice(1, 2); // Removes 'banana' and 'cherry'
console.log(fruits); // Output: ['apple', 'date']
In this example, we started at index 1 and removed two elements ('banana' and 'cherry') from the array.
You can also use splice() to add elements to an array. Here's an example:
const colors = ['red', 'green', 'blue'];
colors.splice(1, 0, 'yellow', 'purple'); // Adds 'yellow' and 'purple' at index 1
console.log(colors); // Output: ['red', 'yellow', 'purple', 'green', 'blue']
In this example, we started at index 1 and added 'yellow' and 'purple' to the array without removing any elements.
You can replace elements in an array using splice() as well. Here's an example:
const animals = ['cat', 'dog', 'elephant', 'giraffe'];
animals.splice(2, 1, 'lion'); // Replaces 'elephant' with 'lion'
console.log(animals); // Output: ['cat', 'dog', 'lion', 'giraffe']
In this example, we started at index 2, removed one element ('elephant'), and added 'lion' in its place.
The splice() method is incredibly useful in various scenarios, such as: