This article mainly shares with you how to use slice() in js. slice() obtains a new array through the index position. This method does not modify the original array, but only returns a new subarray.
Usage: arrayObj.slice(start,end)
arrayObj - original array;
start - required; sets the starting position of the new array; if it is a negative number, it means counting from the end of the array (-1
refers to the last element, -2 refers to the second to last element, and so on).
end - Optional; set the end position of the new array; if this parameter is not filled in, it will default to the end of the array; if it is a negative number, it means counting from the end of the array (- 1 refers to the last element, -2
refers to the second to last element, and so on).
例1:获取仅包含最后一个元素的子数组var arr=[1,2,3,4,5]; arr.slice(-1);//[5]例2:获取不包含最后一个元素的子数组var arr=[1,2,3,4,5]; arr.slice(0, -1);//[1,2,3,4]例3:获取包含 从第二个元素开始的所有元素的子数组var arr=[1,2,3,4,5]; arr.slice(1);//[2,3,4,5]
slice() obtains a new array through the index position. This method does not modify the original array, but only returns a new subarray.
Related recommendations:
php function array_slice() that returns the selected part of the array
10 recommended articles about slice()
The above is the detailed content of How to use slice() in js. For more information, please follow other related articles on the PHP Chinese website!