The slice() method returns a new array object that is a shallow copy (including begin, but not end) of the array determined by begin and end.

The original array will not be changed.

Focus on the

  • The important thing to notice about this function is that the end element is not in the copied array.
  • Array indices start at 0.

Look at the following code:

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

console.log(animals.slice(-2));
// expected output: Array ["duck", "elephant"]

console.log(animals.slice(2, -1));
// expected output: Array ["camel", "duck"]
Copy the code

If you specify a subscript, the array you return will run from the current subscript to the end.

If you supply a negative number, the negative number will count backwards from the last element in the array, which has a value of -1.

The following figure shows the ordering and definition of subscripts.

If BEGIN exceeds the index range of the original array, an empty array is returned.

Extract the index at the end (starting at 0) and end the extraction of the original array element at that index. Slice extracts all elements indexed from begin to end (including begin, but not end).

Slice (1,4) extracts all elements (elements indexed 1, 2, and 3) from the second element through the fourth element in the array.

If this parameter is negative, it indicates the penultimate element in the original array at the end of the extraction. Slice (-2,-1) extracts the penultimate element of the array to the last element (excluding the last element, i.e. only the penultimate element).

If end is omitted, slice extracts all the way to the end of the original array.

If end is greater than the length of the array, Slice will extract all the way to the end of the array.

www.ossez.com/t/javascrip…