【发布时间】:2014-12-02 23:07:56
【问题描述】:
为什么这是替换而不是添加到对象上?
我也尝试过使用this.push() 而不是.concat(),但发生了完全相同的事情,它覆盖了之前添加的对象。
$scope.checkMatchinAnswer = function (required, ans, input) {
$scope.correctAnswers = [];
angular.forEach(required, function (value) {
if (angular.equals(value.answer, ans) && angular.equals(value.id, qid)) {
$scope.correctAnswers = $scope.correctAnswers.concat([{
id: qid,
answer: value.answer
}]);
}
});
}
【问题讨论】:
-
你试过
$scope.correctAnswers.push.apply($scope.correctAnswers, [{...}])吗? -
.apply()有什么不同? -
concat创建一个新数组,push.apply将改变原始对象。 -
请参考:stackoverflow.com/questions/15013016/…。我相信您需要指定在 foreach 循环中使用哪个上下文。
-
我仍然需要它来为每个
.push()或.concat()创建一个新对象,因为我会使用angular.equals()将其与另一个我无法真正调整的对象进行比较第三方 JSON 文件。
标签: javascript angularjs