Angular JS / JavaScript计算一次迭代的次数

时间:2019-03-01 07:51:41

标签: javascript arrays angularjs object iteration

下面有我的代码,我想知道如何获取等于失败的所有$ scope.rm的计数或多少$ scope.percentage <50。

angular.forEach(result1, function (value, key) {

    $scope.percentage = (value.score * 100 / value.total).toFixed(2);

    if ($scope.percentage < 50) {
        $scope.rm = "Failed"
        $rootScope.sendmail = 0

    }else {
        $scope.rm = "Passed"
        $rootScope.sendmail = 1
    }

});

3 个答案:

答案 0 :(得分:4)

在forEach之外获取一个变量并将其分配为零

在该增量之后,当您获得$ scope.rm =“ Failed”

然后您将不会。该条件的循环执行

例如:

var Failedcount=0,Passedcount=0;
angular.forEach(result1, function (value, key) {

       $scope.percentage = (value.score * 100 / value.total).toFixed(2);

                    if ($scope.percentage < 50) {
                        $scope.rm = "Failed"
                        $rootScope.sendmail = 0
                        Failedcount++;

                    }else {
                        $scope.rm = "Passed"
                        $rootScope.sendmail = 1
                        Passedcount++;
                    }

                });
console.log("failed counter",Failedcount)
console.log("passed counter",Passedcount)

答案 1 :(得分:3)

var failedCount = 0;

angular.forEach(result1, function (value, key) {
  $scope.percentage = (value.score * 100 / value.total).toFixed(2);  

  if ($scope.percentage < 50) {
     $scope.rm = "Failed"
     $rootScope.sendmail = 0
     failedCount++;
  }else {
     $scope.rm = "Passed"
     $rootScope.sendmail = 1
  }
});

console.log(' total failed count : '+failedCount);

答案 2 :(得分:2)

在这里我声明了另一个变量以跟踪其失败的次数。

$scope.numberOfFails = 0

然后,每当满足失败条件时,它就增加1,因此每次失败时都会计数。

$scope.numberOfFails = 0
angular.forEach(result1, function(value, key) {

  $scope.percentage = (value.score * 100 / value.total).toFixed(2);

  if ($scope.percentage < 50) {
    $scope.rm = "Failed"
    $rootScope.sendmail = 0
    $scope.numberOfFails++
  } else {
    $scope.rm = "Passed"
    $rootScope.sendmail = 1
  }

});
console.log($scope.numberOfFails)

此后,您将获得$scope.numberOfFails作为失败的正确次数。