【问题标题】:Converting javascript function in AngularJS function在AngularJS函数中转换javascript函数
【发布时间】:2018-05-21 15:00:24
【问题描述】:

我正在尝试将此 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;

【问题讨论】:

  • $scope.array替换angular.array
  • @Saeed.Ataee 遇到同样的错误。
  • 记录$scope.List.Time;并插入样本
  • 显示更多代码,特别是获取$scope.List.Time 的部分。很有可能这是How do I return the response from an asynchronous call?的副本
  • 错误信息表示$scope.List.Time不存在。如果您想让我们知道它为什么不存在,您必须出示minimal reproducible example。否则你必须自己调试代码。

标签: javascript arrays angularjs


【解决方案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;
};

【讨论】:

    猜你喜欢
    • 2016-06-02
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    • 2014-09-09
    • 2019-11-23
    相关资源
    最近更新 更多