如果条件为真,如何递增变量

时间:2018-06-13 22:03:21

标签: javascript arrays angularjs object

如果条件为真,我希望增加变量。

我有一个像

这样的信息的对象
{id: 1, payment: pending}
{id: 2, payment: paid}

这是我到目前为止所做的:

var currentIndex = 0;
  $scope.unpaid = 0;
  $scope.paid = 0;

  const getSessions = () => {
    loginService.getUser().then((response) => {
      var user_id = response.data.id;
      console.log("getUser returning this => ", response.data);
      loginService.getUserSessions(user_id).then((response) => {
        var sessions = response.data;
        console.log(sessions);
        sessions.forEach(e => e.next_class = e.next_class.substring(0, 10));
        sessions.forEach(function (arrayItem) {
          if(arrayItem.payment === "Pending") {
            $scope.unpaid++;
          }else{
            $scope.paid++;
          };
      });
        $scope.new = sessions;
       Date($scope.class).toISOString().slice(0,10);
      })
    })
  };

  getSessions();

我可以使用for each循环访问对象,但我想遍历该对象并检查payment键。如果payment == pending存储在unpaid,而payment == paid则存储在paid

前端会显示有多少未付费会话和付费会显示在数字中,例如:

Unpaid 1

Paid 1

1 个答案:

答案 0 :(得分:1)

我假设对象在一个数组中,我还假设它被称为payments

var paid = 0;
var unpaid = 0;

var payments = [{id: 1, payment: 'paid'}, {id: 2, payment: 'unpaid'}, {id: 3, payment: 'unpaid'}];

for (var payment in payments) { // iterate through all payments
    if (payments[payment].payment == 'paid') { // if the person has paid
        paid++; // count a payment
    } else { // if the person hasn't paid
        unpaid++; // count a non-payment
    }
}

console.log("Paid: " + paid + ", Unpaid: " + unpaid);

此外,您应该将payment设为布尔值,并将其称为paid,其中true表示此人已付款,false表示未付款。 如果您这样做,那么您可以将if条件更改为if (payments[payment].paid) { ... }。好多了!