Home > Article > Web Front-end > Analysis of splice method and slice method in js
The content of this article is about the analysis of splice method and slice method in js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
I just used the splice() method and found that this method returns the deleted array elements. If you want to get the array after deleting the specified elements, just call the original array directly! Because splice() will change the original array! I have never been familiar with the splice() method before, so I will write an essay to record it.
Definition and usage
The splice() method adds/removes items to/from the array, and then returns the deleted item .
Comment: This method will change the original array.
Syntax
arrayObject.splice(index,howmany,item1,…..,itemX)
例子1: var arr = [1,2,3,4] console.log(arr.splice(1,1));//[2]console.log(arr);//[1,3,4]
Analysis: splice() returns the deleted element after deleting the specified element . This method acts on the arr array, so the original array is also changed and becomes [1,3,4]. We can choose the corresponding result according to our needs.
Finally, a method similar to splice is attached :slice
Definition: The slice() method returns selected elements from an existing array.
How to use: arr.slice(start,end); //start is the initial position, end is the end position, and the returned result is a new array from start to end (not taken)
arr.slice(start );//Select from start to the last element
Example:
var arr1 = [1,2,3,4]; console.log(arr1.slice(1)); //[2, 3, 4]console.log(arr1.slice(1,2));//[2]console.log(arr1);//[1,2,3,4]
Analysis: arr1.slice(1) does not specify the end position, and the last element is selected by default (Note: the last element will be selected)
arr1.slice(1,2) specifies starting from 1 and ending with 2, but does not select 2
is different from splice(), after slice() is executed The original array has not changed
Related recommendations:
alertHow to display the results returned by the function method
The above is the detailed content of Analysis of splice method and slice method in js. For more information, please follow other related articles on the PHP Chinese website!