Combed some javascript entry development experience, share, welcome to learn.

What is the

The Slice method creates a shallow copy of a subset of the list without modifying the original list. The slice method should not be confused with the splice method, which modifies the original array.

arr.slice([begin[, end]])
Copy the code

begin

The index is used to extract elements from the original array. If this parameter is negative, it is used to extract the penultimate element from the original array. Slice (-2) is used to extract the penultimate element from the original array to the last element (including the last element). If begin is omitted, slice starts at index 0.

end

The extraction of the original array elements (starting at 0) ends at the 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, 3) from the second element in the original array up to the fourth element.

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 array length, Slice will also extract to the end of the array.

What do you do

Usage 1: Simple copy

const arr2 = arr.slice() / / shallow copy
Copy the code

Usage 2: Get the subarray starting with N

The simplest way to use slice is to extract all elements of the original array starting with N.

arr.slice(1)
Copy the code

Usage 3: Get the first n bytes of an array

To get the first number of the array, we need to use the second argument: end.

When there are two arguments, the slice method returns a collection starting with begin but excluding end.

Since JavaScript arrays start at 0 (the index starts at 0), this makes it very easy to get the first N elements:

const first3 = arr.slice(0.3)
Copy the code

Usage 4: Get the subarray starting at the end N

Another way to use slice is to get the end of the array, using a negative index to count from the end.

This negative index makes it super easy to delete any number of elements. For example, if you just want to grab three

const last3 = arr.slice(-3)
Copy the code

Usage 5: Get a subarray of an array

What if we want to use Slice to get a segment of an array starting from any index?

To do this, we need to convert from (begin, length) to (begin, end). The calculation logic is simple, and we can define a simple function to do this:

const arr1 = arr.slice(begin, begin + length);
Copy the code

Usage 6: Convert an array-like object to an array

A common use of slice on array-like objects is to convert them into actual arrays. Such as:

const args = Array.prototype.slice.call(arguments);
Copy the code