只是出于好奇。

typeof NaN是number似乎不太符合逻辑。就像NaN === NaN或NaN == NaN返回false。这是JavaScript的特性之一吗,或者有什么原因吗?

编辑:谢谢你的回答。然而,让人明白这不是一件容易的事情。阅读答案和维基我明白了更多,但仍然,一句话像

与NaN的比较总是返回无序结果,即使是与NaN本身比较也是如此。比较谓词是信号或非信号,信号版本表示此类比较的无效异常。等式和不等式谓词是非信号,因此x = x返回false可用于测试x是否为静态NaN。

让我头晕目眩。如果有人能把它翻译成人类(而不是数学家)可读的语言,我会很感激。


当前回答

如果使用jQuery,我更喜欢isNumeric检查类型:

console.log($.isNumeric(NaN));  // returns false
console.log($.type(NaN));       // returns number

http://api.jquery.com/jQuery.isNumeric/

其他回答

一个例子

假设我们正在将一个字符串转换为一个数字:

Number("string"); // returns NaN

我们将数据类型更改为数字,但它的值不是数字!

考虑NAN的最好方法是它不是一个已知的数字。这就是为什么NAN != NAN,因为每个NAN值代表一个唯一的未知数字。nan是必要的,因为浮点数的值范围有限。在某些情况下,舍去小数位会丢失,导致出现像1.0/11*11 != 1.0这样的无意义的结果。真正大的值是nan,无穷大就是一个很好的例子。

鉴于我们只有十个手指,任何显示大于10的值的尝试都是不可能的,这意味着这些值必须是nan,因为我们已经丢失了这个大于10的值的真实值。浮点值也是如此,其值超过了浮点数所能容纳的限制。

它是Number类型的特殊值,如POSITIVE_INFINITY

为什么?通过设计

如果使用jQuery,我更喜欢isNumeric检查类型:

console.log($.isNumeric(NaN));  // returns false
console.log($.type(NaN));       // returns number

http://api.jquery.com/jQuery.isNumeric/

Javascript uses NaN to represent anything it encounters that can't be represented any other way by its specifications. It does not mean it is not a number. It's just the easiest way to describe the encounter. NaN means that it or an object that refers to it could not be represented in any other way by javascript. For all practical purposes, it is 'unknown'. Being 'unknown' it cannot tell you what it is nor even if it is itself. It is not even the object it is assigned to. It can only tell you what it is not, and not-ness or nothingness can only be described mathematically in a programming language. Since mathematics is about numbers, javascript represents nothingness as NaN. That doesn't mean it's not a number. It means we can't read it any other way that makes sense. That's why it can't even equal itself. Because it doesn't.