Why is “0 === -0” true in JavaScript?

ε祈祈猫儿з 提交于 2019-12-08 19:10:33

问题


In a recent post on http://wtfjs.com/. An author writes following without explanation which happens to be true.

0 === -0 //returns true

My understanding about === operator is it returns true if operands point to same object.

Also, - operator returns a reference to negative value of operand. With this rule, 0 and -0 should not be the same.

So, why is 0 === -0 ?


回答1:


In fact, 0 and -0 are not the same even at the bit level. However, there is a special case implemented for +/-0 so they compare as equal.

The === operator compares by value when applied to primitive numbers.




回答2:


=== does not always mean point to the same object. It does on objects, but on value types, it compares the value. Hence how this works:

var x = 0;
var y = 0;
var isTrue = (x === y);
document.write(isTrue); // true

JavaScript used IEEE floating point standard where 0 and -0 are two different numbers, however, the ECMAScript standard states the parser must interpret 0 and -0 as the same:

§5.2 (page 12)

Mathematical operations such as addition, subtraction, negation, multiplication, division, and the mathematical functions defined later in this clause should always be understood as computing exact mathematical results on mathematical real numbers, which do not include infinities and do not include a negative zero that is distinguished from positive zero. Algorithms in this standard that model floating-point arithmetic include explicit steps, where necessary, to handle infinities and signed zero and to perform rounding. If a mathematical operation or function is applied to a floating-point number, it should be understood as being applied to the exact mathematical value represented by that floating-point number; such a floating-point number must be finite, and if it is +0 or -0 then the corresponding mathematical value is simply 0.




回答3:


Primitive numbers are not objects. You're doing a value comparison of the numbers, not an identity comparison of objects.

positive zero is equal to negative zero.

This is from the comparison algorithm for the === operator

If Type(x) is Number, then

  • If x is NaN, return false.

  • If y is NaN, return false.

  • If x is the same Number value as y, return true.

  • If x is +0 and y is −0, return true.

  • If x is −0 and y is +0, return true.

  • Return false.



来源:https://stackoverflow.com/questions/11998340/why-is-0-0-true-in-javascript

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