常规推送和 Array.prototype.push.apply 有什么区别 [英] What's the difference between a regular push and an Array.prototype.push.apply
问题描述
我不太明白下面两行代码的区别.在我的代码中,带有apply"的那一行按照我想要的方式工作,而带有常规推送的那一行则不然.
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);
抱歉混淆,我修复了它,以便在那里有推送"方法
sorry for confusion, I fixed it so that it has the "push" method in there
推荐答案
New 1. 将数组推送到项目上.
New 1. That pushes the array onto items.
$scope.items = [1, 2];
result.data.stuff = [3, 4];
$scope.items.push(result.data.stuff);
$scope.items[0] === 1;
$scope.items[1] === 2;
$scope.items[2][0] === 3;
$scope.items[2][1] === 4;
旧的 1. 删除 $scope.items
中的现有引用.
Old 1. Drops the existing reference that was in $scope.items
.
$scope.items = [1, 2];
result.data.stuff = [3, 4];
$scope.items = result.data.stuff;
$scope.items[0] === 3;
$scope.items[1] === 4;
2.将 result.data.stuff
中的所有项目推送到 $scope.items
中,保留现有项目.
2. Pushes all the items from result.data.stuff
into $scope.items
, keeping the existing items.
$scope.items = [1, 2];
result.data.stuff = [3, 4];
Array.prototype.push.apply($scope.items, result.data.stuff);
$scope.items[0] === 1;
$scope.items[1] === 2;
$scope.items[2] === 3;
$scope.items[3] === 4;
这篇关于常规推送和 Array.prototype.push.apply 有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!