【问题标题】:concat and push overrides what has been previously added to the objectconcat 和 push 覆盖之前添加到对象的内容
【发布时间】: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


【解决方案1】:

你似乎让这件事变得更复杂了。

执行以下操作会设置一个新值,这不是您想要的。

$scope.correctAnswers = 

看来您只是想推送新的 vlaues,所以这样做:

$scope.correctAnswers.push({
    id: qid,
    answer: value.answer
})

【讨论】:

    【解决方案2】:

    我的问题是我每次调用时都在创建一个新范围:

    $scope.correctAnswers = [];
    

    我需要在函数之外创建范围并传递之前添加的内容:

        $scope.checkMatchinAnswer = function(required, ans, input) {
    
           if(!input){ 
               $scope.correctAnswers = [];
           }
    
            angular.forEach(required, function (value) {
                   console.log(angular.equals(value.answer, ans), angular.equals(value.id, qid));
                 if(angular.equals(value.answer, ans) != false && angular.equals(value.id, qid) != false){
                        this.push({ id: qid, answer: value.answer });
                 }
            }, $scope.correctAnswers);
            return $scope.correctAnswers;
        }
    

    然后我会在外面使用这个条件:

    if($scope.correctAnswers != []) {
        $scope.checkMatchinAnswer(content.required, ans, $scope.correctAnswers);
    } else {
        $scope.correctAnswers = $scope.checkMatchinAnswer(content.required, ans);
    }
    

    【讨论】:

      猜你喜欢
      • 2016-05-08
      • 2021-07-16
      • 2018-12-13
      • 1970-01-01
      • 2013-05-11
      • 2022-01-20
      • 2014-02-03
      • 2021-06-04
      • 1970-01-01
      相关资源
      最近更新 更多