Array in JavaScript has splice() method that changes the elements of an array, adding new elements as well as removing old.
Syntax is as below:
1 | array.splice(index, howManyElements, [item1, item2, ..., itemN]); |
index: index at which to start changing the array. Starting at 0.
howManyElements: An integer indicating the number of old array elements to remove. Set howManyElements to 0 to not remove any element.
item1, item2, itemN: The elements to add to the array. Not specifying any elements will let splice simply remove elements from the array.
Return Value:
splice() method returns the extracted array based on the passed parameters.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <html> <head> <title>myArray in JavaScript - splice() Method</title> </head> <body> <script type="text/javascript"> var myArr = ["jQuery", "PHP", "HTML", "CSS"]; document.write("Array: " + myArr); var element_removed = myArr.splice(2, 0, "JavaScript"); document.write("<br /><br />After adding an element: " + myArr ); document.write("<br />Element removed is: " + element_removed); document.write("<br />An element is placed at index 2 and none is removed as second paramenter is 0"); element_removed = myArr.splice(3, 1); document.write("<br /><br />After adding an element: " + myArr ); document.write("<br />Element removed is: " + element_removed); document.write("<br />No element is specified as third parameter so 1 element is removed at index 3"); element_removed = myArr.splice(1, 2, "WordPress", "HTML"); document.write("<br /><br />After adding two elements: " + myArr ); document.write("<br />Elements removed are: " + element_removed); </script> </body> </html> |
Output: This will give the following output:
1 2 3 4 5 6 7 8 9 10 11 12 | Array: jQuery,PHP,HTML,CSS After adding an element: jQuery,PHP,JavaScript,HTML,CSS Element removed is: An element is placed at index 2 and none is removed as second paramenter is 0 After adding an element: jQuery,PHP,JavaScript,CSS Element removed is: HTML No element is specified as third parameter so 1 element is removed at index 3 After adding two elements: jQuery,WordPress,HTML,CSS Elements removed are: PHP,JavaScript |
To understand the splice() method in better way Try yourself.
So splice() method for Array in JavaScript is powerful method that let you modify an existing array. You can add, remove elements or replace existing elements.