我只在Firefox的JavaScript控制台中尝试过,但以下语句都没有返回true:
parseFloat('geoff') == NaN;
parseFloat('geoff') == Number.NaN;
我只在Firefox的JavaScript控制台中尝试过,但以下语句都没有返回true:
parseFloat('geoff') == NaN;
parseFloat('geoff') == Number.NaN;
当前回答
NaN是一个特殊的值,不能这样测试。我想和大家分享一个有趣的事情
var nanValue = NaN;
if(nanValue !== nanValue) // Returns true!
alert('nanValue is NaN');
这只对NaN值返回true,是一种安全的测试方式。肯定应该被包装在一个函数中,或者至少被注释,因为测试相同的变量是否彼此不相等显然没有多大意义,呵呵。
其他回答
你应该使用全局isNaN(value)函数调用,因为:
支持跨浏览器 有关文档,请参阅isNaN
例子:
isNaN('geoff'); // true
isNaN('3'); // false
我希望这对你有所帮助。
函数isNotANumber(n) { If (typeof n !== 'number') { 返回true; } == n; }
准确的检查方法是:
//takes care of boolen, undefined and empty
isNaN(x) || typeof(x) ==='boolean' || typeof(x) !=='undefined' || x!=='' ? 'is really a nan' : 'is a number'
只要要测试类型为Number的值是否为NaN,全局函数isNaN将完成工作
isNaN(any-Number);
对于适用于JS中所有类型的通用方法,我们可以使用以下任何一种方法:
ECMAScript-5用户:
#1
if(x !== x) {
console.info('x is NaN.');
}
else {
console.info('x is NOT a NaN.');
}
对于使用ECMAScript-6的人:
#2
Number.isNaN(x);
为了在ECMAScript 5和6中保持一致性,我们也可以为Number.isNan使用这个填充
#3
//Polyfill from MDN
Number.isNaN = Number.isNaN || function(value) {
return typeof value === "number" && isNaN(value);
}
// Or
Number.isNaN = Number.isNaN || function(value) {
return value !== value;
}
请查看这个答案了解更多细节。
试试下面的代码:
isNaN(parseFloat("geoff"))
要检查是否有任何值是NaN,而不仅仅是数字,请参阅这里:如何在Javascript中测试NaN ?