我知道 (-0 === 0) 是真的。我很想知道为什么 -0 < 0 会发生?
当我在 stackoverflow 执行上下文中运行此代码时,它返回 0
.
const arr = [+0, 0, -0];
console.log(Math.min(...arr));
但是当我在浏览器控制台中运行相同的代码时,它会返回
-0
.这是为什么?我试图在谷歌上搜索它,但没有找到任何有用的东西。这个问题可能不会为某个实际示例增加值(value),我想了解 JS 是如何计算它的。 const arr = [+0, 0, -0];
console.log(Math.min(...arr)); // -0
最佳答案
-0
不小于 0
或 +0
, 两个 -0 < 0
和 -0 < +0
返回 False
,您正在混合 Math.min
的行为与 -0
的比较与 0
/+0
.
specification of Math.min
在这一点上很清楚:
b. If number is -0𝔽 and lowest is +0𝔽, set lowest to -0𝔽.
没有这个异常(exception),
Math.min
的行为和 Math.max
将取决于参数的顺序,这可以被认为是一种奇怪的行为——你可能想要 Math.min(x, y)
总是等于 Math.min(y, x)
——所以这可能是一种可能的理由。注: 1997 specification 中已存在此异常。对于
Math.min(x, y)
,所以这不是后来添加的东西。
关于javascript - 为什么 Math.min() 从 [+0, 0, -0] 返回 -0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70450352/