Array: slice()

359 阅读1分钟

slice定义

slice()返回新的数组,该数组是原数组的浅拷贝。

Note: 原数组不会改变。

语法

Array.slice(begin, end)

参数

const arr = [1, 2, 3, 4, 5]

begin: 数组提取的起始位置(从0开始)

1 begin = 1

    const res = arr.slice(1);

    console.log(res); // [2 ,3, 4, 5]

    提取索引1以后的元素(包含1),并返回提取元素组成的新数组

2 begin > 数组长度

    const res = arr.slice(6);

    console.log(res); // []

3 begin < 0 表示从数组末尾开始的第n个元素, 等同于arr.length - Math.abs(begin)

    const res = arr.slice(-2);
    const res1 = arr.slice(3)

    console.log(res); // [4, 5]
    console.log(res1); // [4, 5]

4 begin 省略 等同于 begin = 0

    const res = arr.slice(0);
    const res1 = arr.slice()

    console.log(res); // [1, 2, 3, 4, 5]
    console.log(res1); // [1, 2, 3, 4, 5]

Note: 提取元素索引包含 begin 

end: 数组提取的终止位置(从0开始)

1 end = 3

    const res = arr.slice(1, 3);

    console.log(res); // [2 ,3]

    提取数组第2个元素到第3个元素 (索引为1,2)

2 end > 数组长度 提取到原数组末尾元素 等同于 end = arr.length

    const res = arr.slice(1, 6);
    const res1 = arr.slice(1, 5);

    console.log(res); // [2, 3, 4, 5]
    console.log(res1); // [2, 3, 4, 5]

    提取第二个元素到末尾元素 (索引为1,2,3,4)

3 end < 0 表示提取到末尾第n个元素, 等同于arr.length - Math.abs(begin)

    const res = arr.slice(1, -2);
    const res1 = arr.slice(1, 3)

    console.log(res); // [2, 3]
    console.log(res1); // [2, 3]

    提取第二个元素到倒数第二个元素(索引为1,2)

4 end 省略 等同于 end = arr.length

    const res = arr.slice(1);

    console.log(res); // [2, 3, 4, 5]

    提取第二个元素到末尾元素(索引为1,2,3,4)

Note: 提取元素索引不包含 end 

返回值

返回由提取元素组成的新数组。(不改变原数组)

    const res = arr.slice(1, 4);

    console.log(res); // [2, 3, 4]
    console.log(arr); // [1, 2, 3, 4, 5]

如果有问题或者描述不清的朋友们,欢迎留言一起探讨,如果本文有给你们帮助请帮忙点个赞。