【问题标题】:Initialising number variables with null and checking for empty values用 null 初始化数字变量并检查空值
【发布时间】:2019-01-09 10:46:59
【问题描述】:

最初我必须将组件属性设置为 null,因为我希望在页面加载时输入一个空输入。我需要检查字符串是否为空,但是当它为空时我不能这样做,实际上我可以,从用户的角度来看一切仍然有效,但它会引发错误,所以我想我不应该这样做。那么如何检查带有可为空变量的空字符串呢?

export class ExpensesLogComponent implements OnInit {
  inputHelperTextVisible: boolean = false;
  expenses: number = null;

检查是否为空:

 onKey(event: any) {
    if (event.key === 'Enter') {
      console.log('enter pressed!');
    }
    // error is this.expenses = null
    if (this.expenses.toString() === '') {
      this.inputHelperTextVisible = false;
    } else {
      this.inputHelperTextVisible = true;
    }
  }

【问题讨论】:

  • 使用null 进行初始化对您有何帮助?为什么不将其初始化为空字符串?无论如何,只需添加一个空检查。 if (this.expenses === null || this.expenses.toString() === '')...

标签: angular typescript


【解决方案1】:

你试过删除 toString 吗?

if (this.expenses == null) {
  this.inputHelperTextVisible = false;
} else {
  this.inputHelperTextVisible = true;
}

如果您使用 == 而不是 === 费用,除了检查它是否为空之外,还会检查它是否未定义。

【讨论】:

    【解决方案2】:

    你不需要设置为 null

    export class ExpensesLogComponent implements OnInit {
      inputHelperTextVisible = false;
      expenses: number;
    

    并检查 null 或空

    if (!this.expenses || this.expenses.toString() == '') { }
    

    【讨论】:

      【解决方案3】:

      您有多种选择来避免错误。 但我建议使用嵌套循环之一以避免打字稿出现任何问题。

          // it will work
          if(this.expenses != null) {
             if (this.expenses.toString() === '') {
                this.inputHelperTextVisible = false;
              } else {
                this.inputHelperTextVisible = true;
             }
          } else{
            this.inputHelperTextVisible = false;
          }
      

      【讨论】:

        猜你喜欢
        • 2018-05-02
        • 2011-10-12
        • 1970-01-01
        • 2018-05-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多