NaN 算作假?
NaN counts as false?
我正在阅读 Marijn Haverbeke 的一本书 "Eloquent JavaScript",上面写着:
"The rules for converting strings and numbers to Boolean values state that 0, NaN, and the empty string ( "" ) 算作假,而所有其他值都算作真。"
如果有人向我解释作者说根据转换规则 NaN 算作 false 是什么意思,那就太好了?
我现在看到的:
0 == false; // true
"" == false; // true
NaN == false; // false
0 / 0 == false; // false
是的,我知道 "NaN is not equal to anything, even to the other NaN",但我只是想知道这本书想让我知道什么?
基本上,如果一个变量被分配给 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!')
}
本书想让您知道 JavaScript 将 NaN 计算为假。
var notANumber = 500 / 0;
if(notANumber) {
// this code block does not run
}
else {
// this code block runs
}
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
其他答案是正确的,但重要的是转换为 bool
是在条件中使用的情况下发生的。
这就是为什么:
NaN === false // false
还:
if(NaN) // false because it first does a boolean conversion
// which is the rule you see described
作为旁注,问题中使用的 NaN == false
(注意 ==
与 ===
)实际上进行了从 false
到 [=17= 的类型转换] 根据 ==
运算符。这超出了这个问题的范围,但运算符的差异在其他地方有详细记录。
我正在阅读 Marijn Haverbeke 的一本书 "Eloquent JavaScript",上面写着:
"The rules for converting strings and numbers to Boolean values state that 0, NaN, and the empty string ( "" ) 算作假,而所有其他值都算作真。"
如果有人向我解释作者说根据转换规则 NaN 算作 false 是什么意思,那就太好了?
我现在看到的:
0 == false; // true
"" == false; // true
NaN == false; // false
0 / 0 == false; // false
是的,我知道 "NaN is not equal to anything, even to the other NaN",但我只是想知道这本书想让我知道什么?
基本上,如果一个变量被分配给 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!')
}
本书想让您知道 JavaScript 将 NaN 计算为假。
var notANumber = 500 / 0;
if(notANumber) {
// this code block does not run
}
else {
// this code block runs
}
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
其他答案是正确的,但重要的是转换为 bool
是在条件中使用的情况下发生的。
这就是为什么:
NaN === false // false
还:
if(NaN) // false because it first does a boolean conversion
// which is the rule you see described
作为旁注,问题中使用的 NaN == false
(注意 ==
与 ===
)实际上进行了从 false
到 [=17= 的类型转换] 根据 ==
运算符。这超出了这个问题的范围,但运算符的差异在其他地方有详细记录。