【问题标题】:How to replace NULL% by 0%如何将 NULL% 替换为 0%
【发布时间】:2021-09-20 12:18:35
【问题描述】:

在我的 calculatePercents() 方法中,我应该得到 0% 而不是 NULL%。

在我的 console.log 中,我得到了带有值 NULL 的打印件

 calculatePercents() {
    this.v.global.total.amount = this.v.global.cash.amount + this.v.global.sec.amount;
    console.log("Cash => " + JSON.stringify(this.v.global.total.amount));
    console.log('------------------------');
    this.v.global.cash.percent = (this.v.global.cash.amount / (this.v.global.cash.amount + this.v.global.sec.amount)) * 100;
    console.log(" Global cash " + JSON.stringify(this.v.global.cash.percent));

    this.v.global.sec.percent = (this.v.global.sec.amount / (this.v.global.cash.amount + this.v.global.sec.amount)) * 100;
    console.log(" NULL ???? ==> " + JSON.stringify(this.v.global.sec.percent));

    var totPercent = (this.v.global.cash.percent + this.v.global.sec.percent);

    this.v.global.total.percent = totPercent;

}

请问我怎样才能得到 0 而不是 NULL。

【问题讨论】:

标签: javascript angular typescript


【解决方案1】:

您可以使用|| 运算符设置零

例如:

this.v.global.total.percent = (totPercent||0);

了解更多https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR

【讨论】:

    【解决方案2】:

    对于||,如果第一个值为 false(转换为布尔值),那么它将采用第二个,在这种情况下,它被用作默认值。

    this.v.global.total.percent = totPercent || 0;
    

    【讨论】:

      【解决方案3】:

      你可以在你的方法中试试这个;

      if(this.v.global.cash.amount == null){
               this.v.global.cash.amount = 0
          }
      if(this.v.global.sec.amount == null){
           
               this.v.global.sec.amount = 0
          }
      

      然后你就可以这样做了; (你的方法)

      calculatePercents() {
      this.v.global.total.amount = this.v.global.cash.amount + this.v.global.sec.amount;
      console.log("Cash => " + JSON.stringify(this.v.global.total.amount));
      console.log('------------------------');
      this.v.global.cash.percent = (this.v.global.cash.amount / (this.v.global.cash.amount + this.v.global.sec.amount)) * 100;
      console.log(" Global cash " + JSON.stringify(this.v.global.cash.percent));
      
      this.v.global.sec.percent = (this.v.global.sec.amount / (this.v.global.cash.amount + this.v.global.sec.amount)) * 100;
      console.log(" NULL ???? ==> " + JSON.stringify(this.v.global.sec.percent));
      
      var totPercent = (this.v.global.cash.percent + this.v.global.sec.percent);
      
      this.v.global.total.percent = totPercent;
      

      }

      您的可验证类型可以是“让”。 简单代码:

      let a = null;
      
      if(a==null){
         a=0
      }
      console.log(a);
      // output: 0
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-02
        • 1970-01-01
        • 2018-12-28
        • 2011-06-04
        • 1970-01-01
        • 2019-09-27
        相关资源
        最近更新 更多