我只在Firefox的JavaScript控制台中尝试过,但以下语句都没有返回true:
parseFloat('geoff') == NaN;
parseFloat('geoff') == Number.NaN;
我只在Firefox的JavaScript控制台中尝试过,但以下语句都没有返回true:
parseFloat('geoff') == NaN;
parseFloat('geoff') == Number.NaN;
当前回答
根据IEEE 754,所有涉及NaN的关系都被评估为假,除了!=。因此,例如,如果A或B或两者都是NaN, (A >= B) = false且(A <= B) = false。
其他回答
规则是:
NaN != NaN
isNaN()函数的问题是,在某些情况下,它可能会返回意想不到的结果:
isNaN('Hello') //true
isNaN('2005/12/12') //true
isNaN(undefined) //true
isNaN('NaN') //true
isNaN(NaN) //true
isNaN(0 / 0) //true
检查该值是否真的为NaN的更好方法是:
function is_nan(value) {
return value != value
}
is_nan(parseFloat("geoff"))
对此我看到了一些回应,
但我只用:
function isNaN(x){
return x == x && typeof x == 'number';
}
准确的检查方法是:
//takes care of boolen, undefined and empty
isNaN(x) || typeof(x) ==='boolean' || typeof(x) !=='undefined' || x!=='' ? 'is really a nan' : 'is a number'
如果您的环境支持ECMAScript 2015,那么您可能需要使用Number。isNaN来确保这个值真的是NaN。
isNaN的问题是,如果你将它用于非数值数据,就会应用一些令人困惑的规则(根据MDN)。例如,
isNaN(NaN); // true
isNaN(undefined); // true
isNaN({}); // true
因此,在ECMA Script 2015支持的环境中,您可能希望使用
Number.isNaN(parseFloat('geoff'))
函数isNotANumber(n) { If (typeof n !== 'number') { 返回true; } == n; }