PageYe PageYe - 2 months ago 11
Javascript Question

the order of the execution inner the second argument of apply method

var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
// Prepend all items from arr2 onto arr1
Array.prototype.unshift.apply(arr1, arr2) // arr1 is now [3, 4, 5, 0, 1, 2]


The above is a piece of javascript code.

I know the
array.prototype.unshift
.

I know the
apply
which demands the second argument must be a array or like-array.

But I can't understand why the result is
[3, 4, 5, 0, 1, 2]
but not the
[5, 4, 3, 0, 1, 2]
. Does that mean the arr1 first unshift
5
, second unshift
4
, finally unshift
3
? So it may be concluded that the apply's second argument is excuted from right to left?

can someone put it in details?:~)

Answer Source

The first argument to .apply is the context (the this) and the second is an array of arguments.

So what you're actually doing is this:

[0,1,2].unshift(3,4,5);

MDN reference to how unshift works