splice() method is used to remove or replace element in an array.
var Fruits = new Array ("pears", "mangoes" , "bananas" , "apples"); var FewFruits = Fruits.splice(2,1); document.write(Fruits); document.write(" | " + FewFruits);
On the first line a new array with four elements is created.
On the second line a new array is created using
splice() method. What is (2,1)? “2” represents the index of the element from where to start removing elements and “1” represents the number of the elements to be removed. The element with the index 2 is the third element which is “bananas”. Since only one element will be removed that means only the element “bananas”. If you want to remove two elements then you can use (2,2) instead of (2,1). This will remove the elements “bananas” and “apples”.
The third line write on the document elements of the initial array without the element that was removed (bananas).
The fourth line writes on the document the element of the new array formed with the removed element (bananas).
You can use
splice() method to replace the spliced elements in an array or just to add elements to an array.
var Fruits = new Array ("pears", "mangoes" , "bananas" , "apples"); var FewFruits = Fruits.splice(2,1,"grapes"); document.write(Fruits);
The code replaces the “banana” element with the “grapes” element.
If you just want to add an element to the array and not removing any then just set the first parameter at the index number you want to begin adding the new elements and the second parameter to “0” since you don’t want to remove any element.
var Fruits = new Array ("pears", "mangoes" , "bananas" , "apples"); var FewFruits = Fruits.splice(2,0,"grapes" , "watermelons" , "pineapples"); document.write(Fruits);
The three new elements will be added to the array just before the element with index number 2, which is “bananas”.
No element of the array will be removed since the second parameter is set to “0”. The output will be “pears, mangoes, grapes, watermelons, pineapples, bananas, apples”.