What exactly does [] .slice do
slice
is an array method that extracts subarrays from an array:
The method
slice
takes two arguments, start and end, and returns an array containing the elements of the array from element start to but not including the end of the element (or through the end of the array if the end is undefined ).
For example:
[0,1,2,3,4].slice(2); // [2,3,4]
[0,1,2,3,4].slice(-2); // [3,4]
[0,1,2,3,4].slice(2,4); // [2,3]
[0,1,2,3,4].slice(); // [0,1,2,3,4]
In particular, both slice()
and slice(0)
create a copy of the array. You can then modify the copy without affecting the original, and vice versa.
Additionally, it can also be used with array-like objects:
The function is
slice
intentionally generic; it does not require its this value to be an Array object. Therefore, it can be transferred to other kinds of objects for use as a method.
Therefore, it is often used to create a real array from an array-like object:
[].slice.call({0:0, 1:1, 2:2, length:3}); // [0,1,2]
Note that this trick is no longer needed in ECMAScript 6, because you can use Array.from
:
Array.from({0:0, 1:1, 2:2, length:3}); // [0,1,2]
Having a real array instead of an array-like object has the advantage that you can use array methods on them.
source to share