I don't quite understand the difference between the following two lines of code. In my code, the line with "apply" works the way I want it to, and the line with just regular push doesn't.
So what is really going on when both of these are executed:
//this one does not work the way i want it to
$scope.items.push(result.data.stuff)
//this one works!
Array.prototype.push.apply($scope.items, result.data.stuff);
Edit: sorry for confusion, I fixed it so that it has the "push" method in there
New 1. That pushes the array onto items.
Old 1. Drops the existing reference that was in
$scope.items
.2. Pushes all the items from
result.data.stuff
into$scope.items
, keeping the existing items.push()
will add on one index for every argument you pass in. It does not care what it is adding to the array. What every you tell to add it will add it to the end of the array.When you use apply(), it will take the array that you have supplied as the second argument and convert it to multiple arguments. MDN explains it well, but it basically turns it into
Array.prototype.push()
is a method that adds one or more elements to the end of the array and returns the new length of the array.Array.prototype.push.apply()
takes the original array and an array which contains elements to add to the original array.Example for
Array.prototype.push()
:Example for
Array.prototype.push()
with nested arrays:Example for
Array.prototype.push.apply()
:Example for
Array.prototype.push.apply()
with nested arrays:References:
push
apply
I think
$scope.items = result.data.stuff
not equvivalent toArray.prototype.push.apply($scope.items, result.data.stuff);
because the first reallocates the array (clears the old elements)
try this:
or
$scope.items.push.apply($scope.items, result.data.stuff);
The above on equals to call Array.prototype.push.apply because $scope.items is an array (we think it)
there's an other joiner function:
see:MDN:Function.prototype.apply();
Please note the note on this page:
The
apply()
method calls a function with a giventhis
value, and arguments provided as an array (or an array-like object). All the items within the argsArray(second parameter) will be used forArray.prototype.push
in order.It is the same to :$scope.items.push.apply($scope.items, result.data.stuff)
;Because
$scope.items.push === Array.prototype.push
andapply()
accepts an array-like parameter butFunction.prototype.call()
accepts an arguments list;Briefly speaking,
apply
will translate array-like parameter into pieces for that function.