常规推送和Array.prototype.push.apply之间有什么区别 [英] What's the difference between a regular push and an Array.prototype.push.apply
问题描述
我不太明白以下两行代码之间的区别。在我的代码中,带有apply的行按照我想要的方式工作,而只有常规push的行不会。
I don't quite understand the difference between the following 2 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
推荐答案
新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 <中的现有引用/ code>。
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屋!