在 AngularJS 函数中转换 javascript 函数



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

所以我面临这个错误:

类型错误: 无法读取未定义的属性"0">

我哪里出错了?

编辑:- 我从这部分的服务中得到我的回应:-$scope.List = getAllList;

如果服务实现正确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;
};

最新更新