JavaScript Array splice() Method
You are Here:
JavaScript Array splice() Method
The splice()
method adds/removes items to/from an array, and returns the removed item(s).
Note: This method overwrites the original array.
splice() with startIndex Only
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<script>
var myFruit = ["Mango", "Cherry", "Jackfruit", "Apple"];
myFruit.splice(2);
document.write("myFruit = " +myFruit);
</script>
</body>
</html>
Syntax
Array.splice(startIndex, deleteCount, item1, ..., itemX)
Parameter Values
Value | Type | Explanation |
---|---|---|
startIndex | Required | Specifies the position at which the element to be add/remove. A negative index can be used to specifies the position from reverse order i.e., from right to left. If omitted, the default value is '0'. |
deleteCount | Optional | Specifies the number of items to be removed. If deleteCount is 0 or negative, no elements are removed. If omitted, the default value is the 'length of an array' - 'startIndex'. |
item1, ..., itemX | Optional | Specifies the elements to add to the array, beginning at the start index. If you don't specify any elements, splice() will only remove elements from the array. |
splice() with deleteCount
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<script>
var myFruit = ["Mango", "Cherry", "Jackfruit", "Apple"];
myFruit.splice(2, 1);
document.write("myFruit = " +myFruit);
</script>
</body>
</html>
Adding new Elements
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<script>
var myFruit = ["Mango", "Cherry", "Jackfruit", "Apple"];
myFruit.splice(2, 2, "Banana", "blueberry");
document.write("myFruit = " +myFruit);
</script>
</body>
</html>
Replacing new Elements
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<script>
var myFruit = ["Mango", "Cherry", "Jackfruit", "Apple"];
myFruit.splice(2, 0, "Banana", "blueberry");
document.write("myFruit = " +myFruit);
</script>
</body>
</html>
Reminder
Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.
We are working to cover every Single Concept in JavaScript.
Please do google search for:
Join Our Channel
Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.
This channel is primarily useful for Full Stack Web Developer.