这个是false
,意思是""
是一个数字:
alert(isNaN(""));
这个是NaN
,意思是""
不是数字,不能转换:
alert(parseFloat(""));
我期待第二个代码将 ""
转换为 0
因为 ""
在 IsNaN< 中测试时是一个数字
但我错了!我是疯了还是错过了什么?
最佳答案
parseFloat
尝试从字符串中解析一个数字,其中 as isNaN
converts the argument to number检查之前:
Number("") //0 http://ecma-international.org/ecma-262/5.1/#sec-9.3.1
parseFloat("") //NaN http://ecma-international.org/ecma-262/5.1/#sec-15.1.2.3
显然这是“损坏的”或“令人困惑的”,所以从规范来看:
A reliable way for ECMAScript code to test if a value X is a NaN is an expression of the form X !== X. The result will be true if and only if X is a NaN.
0 !== 0 // false
NaN !== NaN //true
function isExactlyNaN(x) {
return x !== x;
}
关于javascript - JavaScript 中的 ""到底是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10926024/