So many times I see this following expression:
var args = [].slice.call(arguments, 0);
But [].slice.call([1,2,3,4,5], 0)
is exactly [1,2,3,4,5]
.
And isn't it just saying
var args = arguments
?
So what exactly does [].slice
do here?
So many times I see this following expression:
var args = [].slice.call(arguments, 0);
But [].slice.call([1,2,3,4,5], 0)
is exactly [1,2,3,4,5]
.
And isn't it just saying
var args = arguments
?
So what exactly does [].slice
do here?
slice
is an array method which extracts subarrays from an array:
The
slice
method takes two arguments, start and end, and returns an array containing the elements of the array from element start up to, but not including, element end (or through the end of the array if 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]
Specifically, both slice()
and slice(0)
produce a copy of the array. Then you will be able to alter the copy without affecting the original, and vice versa.
Additionaly, it can also be used with array-like objects:
The
slice
function is intentionally generic; it does not require that its this value 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 build a real array from an array-like object:
[].slice.call({0:0, 1:1, 2:2, length:3}); // [0,1,2]
Note this trick is no longer necessary 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.