1.slice (Array)
Usage: Array.slice (start,end)
Explanation: This method is a partial intercept of an array, and returns a copy of the arrays; The parameter start is a truncated start array index, and the end parameter equals the position value of the last character you want to take plus 1 (optional)
?
12345678910111213141516171819202122 |
//如果不传入参数二,那么将从参数一的索引位置开始截取,一直到数组尾
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)
Explanation: The slice method copies part of a string to construct a new string, using the same slice method as the parameter blend array; the end parameter is equal to the position value of the last character you want to take, plus 1.
?
123 |
//举个简单的例子 var a= "i am a boy" ; var b=a.slice(0,6); //"i am a" |
3.splice (Array)
Usage: Array.splice (Start,deletecount,item ...)
Explanation: The Splice method removes one or more arrays from the array and replaces them with a new item. The argument start is the start position of the element removed from the array. The parameter deletecount is the number of elements to remove.
If there are additional parameters, then item is inserted into the position of the removed element. It returns an array containing the elements that were removed.
?
123 |
//举一个简单的例子 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)
Explanation: The Split method splits the string into fragments to create an array of strings. The optional parameter limit limits the number of fragments to be split. The separator parameter can be a string or a regular expression. If
Separator is a null character that returns an array of single characters.
?
123 |
//再举一个简单的例子 var a= "0123456" ; var b=a.split( "" ,3); //b=["0","1","2"] |
Slice,splice and split three functions that are not easy to distinguish in JavaScript