slice method

Compared with the splice method, the slice method does not modify the original array.

1. Grammar and description

Description : Make a shallow copyof the original array through start and end(extract the array elements indexed from start to end)

Syntax :Array.slice([start[, end])

Parameters :

  1. start : start index

  1. end : end index

Return value : return a new array

Whether to change the original array : No

2. Parameters

1. No parameters

Description : Extract the array elements from the starting index (0) until the end

Return value : all array elements from the start index to the end index

Original array : no change

example

var arr = ['A', 'B', 'C', 'D'];
var res = arr.slice()

console.log('arr', arr);
// ['A', 'B', 'C', 'D']
console.log('res', res);
// ['A', 'B', 'C', 'D']
2. There is only one parameter start

Description : Extract the array elements from the start index until the end

  Negative number : means to extract array elements from the reciprocal start index

  Positive number : extract array elements from the start index until the end

Return value : all array elements from the start index to the end index, if the start is greater than the original array length, an empty array is returned

Original array : no change

example

// 1. 正数
var arr = ['A', 'B', 'C', 'D'];
var res = arr.slice(1)

console.log('arr', arr);
// ['A', 'B', 'C', 'D']
console.log('res', res);
// ["B", "C", "D"]

// 2. 负数
var arr = ['A', 'B', 'C', 'D'];
var res = arr.slice(-1)

console.log('arr', arr);
// ['A', 'B', 'C', 'D']
console.log('res', res);
// ["D"]

// 3. 大于数组长度的值
var arr = ['A', 'B', 'C', 'D'];
var res = arr.slice(6)

console.log('arr', arr);
// ['A', 'B', 'C', 'D']
console.log('res', res);
// []
3. There are two parameters start , end

Description : Extract array elements from the start index to the end index (including start, but not including end)

Return value : all array elements from start index to end index

Original array : no change

example

var arr = ['A', 'B', 'C', 'D'];
var res = arr.slice(1, 3)

console.log('arr', arr);
// ["A", "B", "C", "D"]
console.log('res', res);
// ["B", "C"]

Three, pay attention

  1. If only one parameter larger than the length of the array is passed in, an empty array is returned

  1. No matter how the array elements are extracted, the original array remains unchanged

Guess you like

Origin blog.csdn.net/m0_60237095/article/details/129421508