stackjlei stackjlei - 2 months ago 11
Javascript Question

Array.prototype.slice.call(arguments) vs. Array.prototype.slice.apply(arguments)

Previous posts have talked about how

Array.prototype.slice.call(arguments)
work but I don't get why you're using
call
instead of
apply
when apply is used for array-like objects whereas
call
is used on lists of objects separated by commas. Isn't
arguments
an array-like object that should used
apply
instead of
call
?

Answer

If you'd like to pass arguments to slice in array instead of one by one, then there is a difference. You could do it this way

[1, 2, 3, 4, 5, 6, 7]  ---- our example arguments
Array.prototype.slice.call(arguments, 2, 5);

here you pass to slice method 2 and 5 and these are slice arguments to indicate that you want to get items at index 1 to item at index. 4. So most likely it will be 3, 4, 5.

Array.prototype.slice.apply(arguments, [2, 5]);

This does the same but arguments for slice can be passed in an array.

Comments