Javascript splice

JS Array.splice() method adds or deletes array elements, and returns the subarray of deleted elements. This method modifies the target array.

The 1st argument is the start position, the 2nd argument is the number of the elements should be deleted.

var arr = ["be", "32", "color", "9", "u", "2", "3.2", "i","we"];
var ret = arr.splice(3,4); 
alert(ret); //9,u,2,3.2
alert(arr); //be,32,color,i,we

If only one argument is provided, the deleted subarray will be the specified postion to the end of array.

var arr = ["be", "32", "color", "9", "u", "2", "3.2", "i","we"];
var ret = arr.splice(3); 
alert(arr); //be,32,color
alert(ret); //9,u,2,3.2,i,we

The argument with negative value represents its position relative to the last element.

var arr = ["be", "32", "color", "9", "u", "2", "3.2", "i","we"];
var ret = arr.splice(-3); 
alert(arr);  //be,32,color,9,u,2
alert(ret);  //3.2,i,we

ret = arr.splice(-3,2); 
alert(ret);   //3.2, i
alert(arr);  //be,32,color,9,u,2,we

If there are more than 2 arguments, the 3rd and beyond arguments will be added to the array at the position specified by the 1st argument.

var arr = ["be", "32", "color", "9", "u", "2", "3.2", "i","we"];
var ret = arr.splice(3,4, "x", "y"); 
alert(arr); //be,32,color,x,y,i,we
alert(ret); //9,u,2,3.2 © 2024  | Terms of Use | Privacy | Home