我只在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"))

你应该使用全局isNaN(value)函数调用,因为:

支持跨浏览器 有关文档,请参阅isNaN

例子:

 isNaN('geoff'); // true
 isNaN('3'); // false

我希望这对你有所帮助。

NaN是一个特殊的值,不能这样测试。我想和大家分享一个有趣的事情

var nanValue = NaN;
if(nanValue !== nanValue) // Returns true!
    alert('nanValue is NaN');

这只对NaN值返回true,是一种安全的测试方式。肯定应该被包装在一个函数中,或者至少被注释,因为测试相同的变量是否彼此不相等显然没有多大意义,呵呵。

准确的检查方法是:

//takes care of boolen, undefined and empty

isNaN(x) || typeof(x) ==='boolean' || typeof(x) !=='undefined' || x!=='' ? 'is really a nan' : 'is a number'

marksyzm的答案工作得很好,但它不会为无穷大返回false,因为无穷大在技术上不是一个数字。

我想出了一个isNumber函数来检查它是否是一个数字。

函数isNumber(i) isNaN(i && i !== true ?编号(i): parseFloat(i)) &&[编号。POSITIVE_INFINITY, Number.NEGATIVE_INFINITY].indexOf(i) == -1; } console.log (isNumber(∞)); console.log (isNumber(“asdf ")); console.log (isNumber (1.4)); console.log (isNumber(南)); console.log (isNumber (Number.MAX_VALUE)); console.log (isNumber (" 1.68 "));

更新: 我注意到这段代码在某些参数上失败了,所以我改进了它。

function isNumber(i) {//function for checking if parameter is number if(!arguments.length) { throw new SyntaxError("not enough arguments."); } else if(arguments.length > 1) { throw new SyntaxError("too many arguments."); } else if([Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY].indexOf(i) !== -1) { throw new RangeError("number cannot be \xB1infinity."); } else if(typeof i === "object" && !(i instanceof RegExp) && !(i instanceof Number) && !(i === null)) { throw new TypeError("parameter cannot be object/array."); } else if(i instanceof RegExp) { throw new TypeError("parameter cannot be RegExp."); } else if(i == null || i === undefined) { throw new ReferenceError("parameter is null or undefined."); } else { return !isNaN(i && i !== true ? Number(i) : parseFloat(i)) && (i === i); } } console.log(isNumber(Infinity)); console.log(isNumber(this)); console.log(isNumber(/./ig)); console.log(isNumber(null));