1 Splice () 1.1 Description
The splice () method adds/deletes an item to/from the array, and then returns the item that was deleted. The method changes the original array . Link
1.2 Syntax
Arrayobject.splice (index,howmany,item1,....., ItemX)
Parameters
Index: Required. An integer that specifies the location of the Add/remove item, using a negative number to specify the position from the end of the array.
Howmany: Required. The number of items to delete. If set to 0, the item is not deleted.
Item1, ..., ItemX: Optional. Adds a new item to the array.
return value
1.3 Example
Add Item (function () {var arr = [0, 1, 2, 3, 4]; Arr.splice (1, 0, 9, 10); Index location/delete quantity/optional, add item, can multiple Console.log (arr); [0, 9, 10, 1, 2, 3, 4]} ();//delete item (function () {var arr = [0, 1, 2, 3, 4]; Arr.splice (1, 2); Console.log (arr); [0, 3, 4]} ());//delete and add items (function () {var arr = [0, 1, 2, 3, 4]; Arr.splice (1, 2, 9, 10, 11); Console.log (arr); [0, 9, 10, 11, 3, 4]} ());
2 Slice () 2.1 Description
The slice () method returns the selected element from an existing array. Instead of modifying the array, the method returns a sub-array .
2.2 Syntax
Arrayobject.slice (Start,end)
Parameters
Start: Required. Specify where to start the selection. If it is a negative number, it specifies the position from the end of the array. In other words, 1 refers to the last element, 2 refers to the second-lowest element, and so on.
End: Optional. Specifies where to end the selection. The parameter is the array subscript at the end of the array fragment. If this parameter is not specified, then the segmented array contains all elements from start to end of the array. If this parameter is a negative number, it specifies the element starting from the end of the array.
return value
2.3 Example
Intercept the middle section (function () { var arr = [0, 1, 2, 3, 4]; arrs = arr.slice (1, 3); //start from index 1 to index 3, do not include index 3 items console.log (ARRS); //[1, 2]} ());//intercept middle to last (function () { var Arr = [0, 1, 2, 3, 4]; arrs = arr.slice (1); //end is empty, starting from index 1 to end console.log (ARRS); //[1, 2, 3, 4]} ()) ;//Get the last item (function () { var arr = [0, 1, 2, 3, 4]; arrs = arr.slice ( -1); // -1 a project to the last, -1 is the last, -2 the penultimate one console.log (ARRS); //[4]} ());//Exclude the last item (function () { var arr = [0, 1, 2, 3, 4]; arrs = arr.slice (0 , -1); // the first to the third-1, does not contain the first 1 (last) console.log (ARRS); //[0, 1, 2, 3]} ());
JavaScript methods Splice () and slice ()
This article from "Do not know not to ask" blog, please be sure to keep this source http://mazey.blog.51cto.com/12997993/1954610
JavaScript methods Splice () and slice ()