语法
slice(start,end)
方法可从已有数组中返回选定的元素,返回一个新数组,包含从start到end(不包含该元素)的数组元素。
- start参数:必须,规定从何处开始选取,如果为负数,规定从数组尾部算起的位置,-1是指最后一个元素。
- end参数:可选(如果该参数没有指定,那么切分的数组包含从start倒数组结束的所有元素,如果这个参数为负数,那么规定是从数组尾部开始算起的元素)。
例如:
[1,2,3,4,5].slice(1,3); 返回索引为[1,3)的内容,即[2,3]
注意
-
该方法不会改变原数组,而是返回一个子数组。
-
如果想删除数组中的一段元素,应该使用Array.splice()方法。
示例
let arr = [1,2,3,4,5];
let res1 = arr.slice(1);
let res2 = arr.slice(1,3);
let res3 = arr.slice(2);
let res4 = arr.slice(0,5);
// 会报错
// let res5 = arr.slice(0,6);
console.log(arr);
console.log(res1);
console.log(res2);
console.log(res3);
console.log(res4);
输出如下
[ 1, 2, 3, 4, 5 ]
[ 2, 3, 4, 5 ]
[ 2, 3 ]
[ 3, 4, 5 ]
[ 1, 2, 3, 4, 5 ]