Home  >  Article  >  Web Front-end  >  Analysis of splice method and slice method in js

Analysis of splice method and slice method in js

不言
不言Original
2018-08-18 16:43:512296browse

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.

Official description:

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

 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

php Receive shell After returning the results, the solution to Chinese garbled characters_PHP tutorial

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn