Why is IsNaN(x) different from x == NaN where x = NaN [duplicate]

霸气de小男生 提交于 2019-11-30 20:10:31

问题


Why are these two different?

var x = NaN; //e.g. Number("e");
alert(isNaN(x)); //true (good)
alert(x == NaN); //false (bad)

回答1:


Nothing is equal to NaN. Any comparison will always be false.

In both the strict and abstract comparison algorithms, if the types are the same, and either operand is NaN, the result will be false.

If Type(x) is Number, then

  • If x is NaN, return false.
  • If y is NaN, return false.

In the abstract algorithm, if the types are different, and a NaN is one of the operands, then the other operand will ultimately be coerced to a number, and will bring us back to the scenario above.




回答2:


The equality and inequality predicates are non-signaling so x = x returning false can be used to test if x is a quiet NaN.

Source

This is the rule defined in IEEE 754 so full compliance with the specification requires this behavior.




回答3:


The following operations return NaN

The divisions 0/0, ∞/∞, ∞/−∞, −∞/∞, and −∞/−∞
The multiplications 0×∞ and 0×−∞
The power 1^∞
The additions ∞ + (−∞), (−∞) + ∞ and equivalent subtractions.
Real operations with complex results:

The square root of a negative number
The logarithm of a negative number
The tangent of an odd multiple of 90 degrees (or π/2 radians)
The inverse sine or cosine of a number which is less than −1 or greater than +1.

The following operations return values for numeric operations. Hence typeof Nan is a number. NaN is an undefined number in mathematical terms. ∞ + (-∞) is not equal to ∞ + (-∞). But we get that NaN is typeof number because it results from a numeric operation.

From wiki:



来源:https://stackoverflow.com/questions/14986361/why-is-isnanx-different-from-x-nan-where-x-nan

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!