The splice method of the JavaScript Array object can be used to add and/or remove elements from an array.
The splice method takes 1 to n parameters:
1: The array index at which changes will begin
2: How many array elements to remove
3-n: New array elements
var aryTest = [1,2,3,4];
document.write(aryTest.splice(2));
The preceding example uses splice to remove all elements after element 2 from the array. Note that the splice method returns the elements it has removed from the array, so in this case the return value is ‘3,4.’ The array itself, however, contains ‘1,2.’
A second parameter can be passed to splice to specify how many elements to remove from the array after the array index at which changes started.
var aryTest = [1,2,3,4];
document.write(aryTest.splice(2,1));
The preceding example uses splice to remove the third element from the array, leaving the array with ‘1,2,4.’
After the second parameter, additional parameters can be provided to add items to the array in the place were elements were removed.
var aryTest = [1,2,3,4];
document.write(aryTest.splice(2,1,7));
The preceding example will remove 3 from the array and replace it will 7.
Related Articles:
JavaScript Arrays