我不太明白下面两行代码的区别。在我的代码中,带有“应用”的行按照我想要的方式工作,而带有常规推送的行则没有。
那么当这两个都被执行时到底发生了什么:
//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);
编辑:抱歉造成混淆,我修复了它,以便它具有“推送”方法
最佳答案
新 1. 将数组推送到项目上。
$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
中的现有引用。
$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
中,保留现有项目。
$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;
关于javascript - 常规推送和 Array.prototype.push.apply 之间有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35638511/