NaN算错了吗?

时间:2017-05-02 20:21:18

标签: javascript type-conversion nan

我正在读一本书" Eloquent JavaScript"由Marijn Haverbeke说道:

"将字符串和数字转换为布尔值的规则规定0,NaN和空字符串("")计为false,而所有其他值都计为true。 "

如果有人根据转换规则说NaN算错,那么有人会解释我作者的意思会不会很好?

我现在可以看到:

for i in range(len(word) // 2):
    print(word[2*i:2*i+2])

是的我知道" NaN不等于任何东西,即使对于其他NaN",但我只是想知道这本书要我知道什么?

4 个答案:

答案 0 :(得分:3)

基本上,如果将变量分配给NaN,则在条件语句中使用它时将评估为false。例如:

var b = NaN;

if(b){//code will never enter this block
    console.log('the impossible has occurred!')
}

如果输入无效,也是如此:

var input = "abcd"
var num = parseFloat(input);

if(num){
    console.log('the impossible has occurred!')
}

答案 1 :(得分:1)

var a = NaN;
var b = null;
var c;
var d = false;
var e = 0;

document.write(a + " " + b + " " + c + " " + d + " "+ e + "<br>");
if(a || b || c || d || e){
  document.write("Code won't enter here");
}
if(a || b || c || d || e || true){
  document.write("Code finally enters");
}

参考:link

答案 2 :(得分:1)

其他答案是正确的,但重要的是,在条件中使用的情况下会转换为bool

这就是原因:

NaN === false // false

然而:

if(NaN) // false because it first does a boolean conversion
        // which is the rule you see described

作为旁注,问题(注释NaN == false vs ==)中使用的===实际上是从false0的类型转换==运算符。它超出了这个问题的范围,但操作员的差异在其他地方有很好的记录。

答案 3 :(得分:0)

本书希望您了解JavaScript将NaN评估为false。

var notANumber = 500 / 0;
if(notANumber) {
     // this code block does not run
}
else {
        // this code block runs
}
相关问题