Distinguishing splice (), slice (), split () function

1.slice (array)

Usage: array.slice (start, end)

Explanation: This method is a partial cutaway array, and returns a copy of the array; start is the start parameter taken array index, end value of the last parameter is equal to the position of the character you want to take a plus (optional)

//如果不传入参数二,那么将从参数一的索引位置开始截取,一直到数组尾
var a=[1,2,3,4,5,6];
var b=a.slice(0,3);    //[1,2,3]
var c=a.slice(3);       //[4,5,6]

//如果两个参数中的任何一个是负数,array.length会和它们相加,试图让它们成为非负数,举例说明:
//当只传入一个参数,且是负数时,length会与参数相加,然后再截取
var a=[1,2,3,4,5,6];
var b=a.slice(-1);    //[6]

//当只传入一个参数,是负数时,并且参数的绝对值大于数组length时,会截取整个数组
var a=[1,2,3,4,5,6];
var b=a.slice(-6);    //[1,2,3,4,5,6]
var c=a.slice(-8);    //[1,2,3,4,5,6]

//当传入两个参数一正一负时,length也会先于负数相加后,再截取
var a=[1,2,3,4,5,6];
var b=a.slice(2,-3);    //[3]

//当传入一个参数,大于length时,将返回一个空数组
var a=[1,2,3,4,5,6];
var b=a.slice(6);  //[]

2.slice (string)

Usage: string.slice (start, end)

Interpretation: The slice method copies a part of the string to construct a new string, and the use of smoothing parameter array slice method like; end position of the parameter value is equal to take your last character plus 1

//举个简单的例子
var a="i am a boy";
var b=a.slice(0,6);    //"i am a"

3.splice (array)

用法:array.splice(start,deleteCount,item...)

Explain: splice method of removing one or more of the array from the array, and replaces them with new item. Parameter start is the start location to remove elements from an array of array. DeleteCount parameter is the number of elements to be removed.

If there are additional parameters, then the item will be inserted into the position of the element to be removed. It returns an array containing the elements to be removed.

//举一个简单的例子
var a=['a','b','c'];
var b=a.splice(1,1,'e','f');    //a=['a','e','f','c'],b=['b']

4.split (string)

Usage: string.split (separator, limit)

Explain: split method of this string into segments to create an array of strings. Optional parameter limit can limit the number of divided segments. separator parameter can be a string or a regular expression. in case

separator is a blank character, returns an array of a single character.

//再举一个简单的例子
var a="0123456";
var b=a.split("",3);    //b=["0","1","2"]

Guess you like

Origin www.cnblogs.com/wangtong111/p/11223365.html