gpt4 book ai didi

javascript - 为什么 "0 === -0"在 JavaScript 中为真?

转载 作者:数据小太阳 更新时间:2023-10-29 04:30:18 25 4
gpt4 key购买 nike

在最近关于 http://wtfjs.com/ 的帖子中.一位作者在没有解释的情况下写了以下内容,这恰好是真的。

0 === -0 //returns true

我对 === 运算符的理解是,如果操作数指向同一个对象,它会返回 true。

此外,- 运算符返回对操作数负值的引用。使用此规则,0 和 -0 不应相同。

那么,为什么 0 === -0 ?

最佳答案

=== 并不总是意味着指向同一个对象。它在对象上执行,但在值类型上,它比较值。因此这是如何工作的:

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

JavaScript 使用 IEEE 浮点标准,其中 0 和 -0 是两个不同的数字,但是,ECMAScript standard声明解析器必须将 0 和 -0 解释为相同:

§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 explicitsteps, 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.

关于javascript - 为什么 "0 === -0"在 JavaScript 中为真?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11998340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com