【发布时间】: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