javascript .push通过复制新值

时间:2015-05-01 10:17:59

标签: javascript arrays

(这是在Angular中)我需要创建一个数组数组以在图表中显示。这些值由以下代码生成:

$scope.getData = function() {
  $scope.series.length = 0
  $scope.allData.length = 0
  var dataArray = [];
  var dateArray = ["2015-04-03 00:00:00", "2015-04-04 00:00:00", "2015-04-05 00:00:00", "2015-04-06 00:00:00", "2015-04-07 00:00:00"]

  for (var i = 0 ; i < $scope.dataDisplayModel.length ; i++) {
    if ($scope.dataDisplayModel[i].checked === true) {
      var field = $scope.dataList.fields.indexOf($scope.dataDisplayModel[i].field)
      dataArray.length = 0;

      for (var j = 0 ; j < 5 ; j++) {
        var arrayList = $filter('filter')($scope.dataList.values, dateArray[j], true);
        var sum = _.sum(arrayList, field);
        dataArray.push(sum);
      }
      $scope.allData.push(dataArray);
    }
  }
}

使用:

$scope.allData = the target array
dataDisplayModel = an array of objects containing field names and a checked proporty
$scope.dataList = json array containing the original data

出于某种原因,每次我推送到$ scope.allData时,它都会覆盖以前的数组,从而留下重复数据。所以,如果我检查了2个字段

$scope.allData = [[ARRAY2],[ARRAY2]]

如果我检查了3个字段

$scope.allData = [[ARRAY3],[ARRAY3],[ARRAY3]]

等。 我无法弄清楚为什么它会一直覆盖我以前的阵列。

1 个答案:

答案 0 :(得分:3)

每次推送同一个(同一参考)之前,只需创建一个 new 本地数组:

    $scope.getData = function() {
      $scope.series.length = 0
      $scope.allData.length = 0

      var dateArray = ["2015-04-03 00:00:00", "2015-04-04 00:00:00", "2015-04-05 00:00:00", "2015-04-06 00:00:00", "2015-04-07 00:00:00"]

      for (var i = 0 ; i < $scope.dataDisplayModel.length ; i++) {
        var dataArray = []; // create a new local var each iteration
        if ($scope.dataDisplayModel[i].checked === true) {
          var field = $scope.dataList.fields.indexOf($scope.dataDisplayModel[i].field);


          // dataArray.length = 0; // this will not clear the array!!!!

          for (var j = 0 ; j < 5 ; j++) {
            var arrayList = $filter('filter')($scope.dataList.values, dateArray[j], true);
            var sum = _.sum(arrayList, field);
            dataArray.push(sum);
          }
          $scope.allData.push(dataArray);
        }
      }
    }