转换AngularJS函数中的javascript函数

时间:2018-05-21 15:00:25

标签: javascript arrays angularjs

我正在尝试将此JavaScript函数转换为AngularJS,但因为我是AngularJS中的新手而获得的错误很少。

var array = [5, 5, 7, 9, 9, 9];
var max = array[0],
    total = 0;
array.forEach((a) => {
  if (a == max) {
    total += max;
  } else if (a > max) {
    max = total = a;
  }
});
console.log("total:", total);

var array[]现在来自 GET 数据,我在AngularJS代码中执行了此操作。

$scope.List = getAllList;

$scope.deptime =function (){
   $scope.array = $scope.List.Time;
   console.log($scope.array);
   $scope.max = $scope.array[0], $scope.total = 0;
   angular.array.forEach((a)=>{

       if(a==$scope.max){
          $scope.total+=$scope.max;
       }
       else if(a>$scope.max){
          $scope.max = $scope.total = a;
       }

    });
    console.log("total:"+$scope.total);
};
$scope.deptime();

所以我遇到了这个错误:

  

TypeError:无法读取未定义的属性“0”

我哪里错了?

编辑: - 我在此部分的服务中收到了我的回复: - $scope.List = getAllList;

1 个答案:

答案 0 :(得分:1)

如果getAllList服务实现正确,请将您的代码更改为此

getAllList()
  .then(function(res) {
    $scope.List = res;
    $scope.deptime();
  });

还会在 deptime 中将angular.array更改为$scope.array

$scope.array.forEach((a) => {
  if (a == $scope.max) {
    $scope.total += $scope.max;
  } else if (a > $scope.max) {
    $scope.max = $scope.total = a;
  }
});

另外,如果您在功能之外不需要maxtotalarray,请将您的功能更改为

$scope.deptime = function() {
  let array = $scope.List.Time;
  let max = $scope.array[0],
    total = 0;
  $scope.array.forEach((a) => {
    if (a == max) {
      total += max;
    } else if (a > max) {
      max = total = a;
    }
  });
  console.log("total:" + total);
  return total;
};