javascript 为什么 NaN != 未定义?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16106365/
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 03:16:58  来源:igfitidea点击:

Why does NaN != undefined?

javascriptvariables

提问by oodavid

According to the Mozilla docs:

根据Mozilla 文档

The undefined value converts to NaN when used in numeric context.

在数字上下文中使用时,未定义的值会转换为 NaN。

So why do both of the following equate to true?:

那么为什么以下两种情况都为真呢?:

NaN != undefined
NaN !== undefined

I could understand Nan !== undefinedas the variable type would be different...

我可以理解Nan !== undefined为变量类型会有所不同......

回答by Naftali aka Neal

NaN is by definition"Not a Number"

NaN根据定义是不是数字

That does not mean it is undefined -- it isclearly defined-- but undefined in a sense that it is nota number.

这并不意味着它是未定义的——它明确定义的——而是在某种意义上它不是数字的未定义。

回答by Ja?ck

This is because, according to Section 4.3.23 of ECMAScript Language SpecificationNaNis defined as:

这是因为,根据ECMAScript 语言规范的第 4.3.23 节NaN定义为:

number value that is a IEEE 754 “Not-a-Number” value

作为 IEEE 754“非数字”值的数字值

So it's a number and not something undefined or null. The value is explained further in Section 8.3

所以它是一个数字,而不是未定义或空的东西。该值在第 8.3 节中进一步解释

...; to ECMAScript code, all NaN values are indistinguishable from each other.

...; 对于 ECMAScript 代码,所有 NaN 值都无法区分。

Equality comparisons with NaNare defined in Section 11.9.3:

第 11.9.3 节NaN中定义了等式比较:

The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows: If Type(x) is Number, then:

If x is NaN, return false.

If y is NaN, return false.

比较 x == y,其中 x 和 y 是值,产生真或假。这样的比较执行如下:如果 Type(x) 是 Number,则:

如果 x 是 NaN,则返回 false。

如果 y 是 NaN,则返回 false。

For the purpose of comparison you should use isNaN()instead:

出于比较的目的,您应该isNaN()改用:

isNaN(NaN)
// true

Update

更新

The value of +undefinedis not-a-number, but it's a number nonetheless (albeit with a special value) and therefore not undefined. Just like how casting undefinedto a string yields a string value that's defined.

的值+undefined不是数字,但它仍然是一个数字(尽管具有特殊值),因此不是未定义的。就像转换undefined为字符串如何产生定义的字符串值一样。