简体   繁体   中英

Angular 2 - if condition getting true for all values

I have been stuck at a point, my if condition is returning true for all conditions, I am checking that a value is greater or not.

Code:

 hideAmountModal() {
    var self = this;
    self.home_delivery_charge = self.storeService.fetchHomedeliveryData(self.shopId);
    self.home_delivery_charge.subscribe((res: any) => {
      for (var i = 0; i < res.length; i++) {
        if (self.deliveryData.delivery_charge > res[i].amount) {
          self.check_delivery_charge = true;
          console.log('Deliverycharge',self.deliveryData.delivery_charge,'result',res[i].amount);
          console.log('deliver charge is greater',self.check_delivery_charge);
        }
        else if (self.deliveryData.delivery_charge < res[i].amount){
            self.check_delivery_charge = false;
        }
      }
    })
    self.DeliveryChargeValue = true
    self.selectAmountModal.hide();
  } 

From the console what I get is below:

在此处输入图片说明

Where have I gone wrong?

Try converting both values to number type

if (parseInt(self.deliveryData.delivery_charge) > parseInt(res[i].amount)) {
}

Change your if condition from:

if (self.deliveryData.delivery_charge > res[i].amount)

To this:

if (Number(self.deliveryData.delivery_charge) > Number(res[i].amount))         

Doing this, you would be explicitly type-casting your input type into number.

Remember: You'll get NaN (Not-a-Number) if your input can't be converted to number type.

In case you don't want this behavior you could always use parseInt which uses Javascript's Number() function under-the-hood as shown here .

Be careful because you are not handling the equal case, which you should include on the else if . Can you check that the values that you are comparing are numbers? This is probably the problem.

You console.log only value when is true

Try add console.log here :

else if(self.deliveryData.delivery_charge < res[i].amount) {
  self.check_delivery_charge = false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM