【问题标题】:Angular - Why does Number.isNaN return false for a non-empty string?Angular - 为什么 Number.isNaN 为非空字符串返回 false?
【发布时间】:2018-05-03 01:15:29
【问题描述】:

我有一个允许用户选择值的下拉菜单。当所选项目发生变化时,它会调用我的组件中的一个函数 (onDropdownChange)。传递给onDropdownChange 的值可以是字符串(“请选择一个选项”)或所选值的索引号。

这是我的 TypeScript 文件中的 onDropdownChange:

onDropdownChange(id: any) {
  if(Number.isNaN(id)){
    this.selectedIndex = null;
    this.isItemSelected = false;
  }
  else{
    this.selectedIndex  = id;
    this.isItemSelected = true;
  }
}

当 id 的值为“请选择一个选项”时,isNaN 返回false。为什么?

当我在下面的代码中使用“+”一元运算符返回字符串的数字表示时,isNan 正确返回true。为什么?

onDropdownChange(id: any) {
  // convert id to a number representation using '+'
  if(Number.isNaN(+id)){
    this.selectedIndex = null;
    this.isItemSelected = false;
  }
  else{
    this.selectedIndex  = id;
    this.isItemSelected = true;
  }
}

这是我的html模板中的相关代码:

            <select class="form-control" (change)="onItemChange($event.target.value)">
              <option> Please select </option>
              <option *ngFor="let item of items; let i=index" [value]="i" [selected]="i === selectedIndex"> Item {{i+1}}</option>
            </select>

【问题讨论】:

  • 回答此类问题的最佳方式是始终先查阅文档。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • When the value of id is "Please select an option", isNaN returns false. Why? 好吧,这有点像循环逻辑,但是......它是false,因为字符串"Please select an option" 不是值NaN。它几乎在那里描述了自己。

标签: javascript angular


【解决方案1】:

Number.isNaN()

Number.isNaN() 方法判断传入的值是否为 NaN,其类型是否为 Number。它是原始全局 isNaN() 的更强大版本。

如果id是字符串,那么它不是数字,所以Number.isNaN()返回false:

console.log(Number.isNaN('Please select an option'));
console.log(Number.isNaN('foo'));

使用Number.isNaN() 的唯一时间是当您想要检查someVariable === NaN 时,它本身不起作用,因为NaN !== NaN

对于您的情况,只需使用普通的isNaN

console.log(isNaN('Please select an option'));
console.log(isNaN('foo'));

【讨论】:

    【解决方案2】:

    isNaN(id) === Number.isNaN(+id)

    x 只有一个值,Number.isNaN(x) 的计算结果为真:NaN

    console.log( Number.isNaN( NaN ) );
    console.log( Number.isNaN( 'foo' ) );
    console.log( Number.isNaN( {} ) );
    console.log( isNaN( '5' ) );
    console.log( Number.isNaN( 0 ) );

    这与全局 isNaN 函数相反,它在将 NaN 强制转换为数字后返回 true

    console.log( isNaN( NaN ) );
    console.log( isNaN( 'foo' ) );
    console.log( isNaN( {} ) );
    console.log( isNaN( '5' ) );
    console.log( Number.isNaN( 0 ) );

    这些函数都不是用来测试它们的参数是否不是number。它们都用于测试它们的论点 是否为数字 NaN

    【讨论】:

      猜你喜欢
      • 2017-12-14
      • 1970-01-01
      • 2020-08-11
      • 1970-01-01
      • 2014-09-25
      • 1970-01-01
      • 1970-01-01
      • 2020-05-23
      • 2018-05-05
      相关资源
      最近更新 更多