javascript 为什么 NaN === NaN 是假的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19955898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:20:33  来源:igfitidea点击:

Why is NaN === NaN false?

javascriptnan

提问by Ionic? Biz?u

Why does NaN === NaNreturn falsein Javascript?

为什么 在 Javascript中NaN === NaN返回false

> undefined === undefined
true
> NaN === NaN
false
> a = NaN
NaN
> a === a
false

On the documentation pageI see this:

文档页面上,我看到了这个:

Testing against NaN

Equality operator (==and ===) cannot be used to test a value against NaN. Use isNaNinstead.

针对 NaN 进行测试

相等运算符(=====)不能用于测试值NaN。使用isNaN来代替。

Is there any reference that answers to the question? It would be welcome.

是否有任何参考资料可以回答这个问题?这将是受欢迎的。

采纳答案by SLaks

Strict answer: Because the JS spec says so:

严格回答:因为 JS 规范是这样说的

  • If Type(x) is Number, then
    • If x is NaN, return false.
    • If y is NaN, return false.
  • 如果 Type(x) 是 Number,则
    • 如果 x 是 NaN,则返回 false。
    • 如果 y 是 NaN,则返回 false。


Useful answer: The IEEE 754 spec for floating-point numbers (which is used by all languages for floating-point) says that NaNs are never equal.

有用的答案:浮点数的 IEEE 754 规范(所有语言都使用浮点数)说 NaN 永远不相等。

回答by NPE

This behaviour is specified by the IEEE-754 standard(which the JavaScript spec follows in this respect).

此行为由IEEE-754 标准指定(JavaScript 规范在这方面遵循该标准)。

For an extended discussion, see What is the rationale for all comparisons returning false for IEEE754 NaN values?

有关扩展讨论,请参阅对于 IEEE754 NaN 值返回 false 的所有比较的基本原理是什么?

回答by Mehedi Hasan

Although either side of NaN===NaNcontains the same value and their type is Numberbut they are not same. According to ECMA-262, either side of ==or ===contains NaNthen it will result false value.

尽管 的任一侧NaN===NaN包含相同的值且它们的类型是Number但它们不相同。根据 ECMA-262,无论是一边==还是===包含NaN,都会导致错误值。

you may find a details rules in here-

您可以在此处找到详细规则-

http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3

http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3