为什么 ( 无穷大 | 0 ) === 0?
我正在摆弄 JavaScript 中的按位运算符,我发现有一件事值得注意。
按位或运算符返回1
如果两个输入位之一为1
,则作为输出位。所以这样做 x | 0
总是返回 x
,因为 | 0
没有效果:
( 1 | 0 ) === 1
( 0 | 0 ) === 0
但是,当我计算 Infinity 时| 0
,我得到0
。在我看来,这是令人惊讶的,因为通过上面的计算应该得到Infinity
。毕竟,( x | 0 ) === x
。
我找不到 ECMAscript 规范中明确定义的位置,所以我想知道 ( Infinity | 0 ) === 0 到底意味着什么。也许这就是
Infinity
在内存中的存储方式?如果是这样,怎么可能仍然是做 | 0
操作会导致它返回 0
,而 | 0
不应该做任何事情?
I'm fiddling around with bitwise operators in JavaScript and there is one thing I find remarkable.
The bitwise or operator returns 1
as output bit if one of the two input bits are 1
. So doing x | 0
always returns x
, because | 0
has no effect:
( 1 | 0 ) === 1
( 0 | 0 ) === 0
However, when I calculated Infinity | 0
, I got 0
. This is surprising in my opinion, because by the above one should get Infinity
. After all, ( x | 0 ) === x
.
I cannot find where in the ECMAscript specification this is explicitly defined, so I was wondering what exactly implies that ( Infinity | 0 ) === 0
. Is is perhaps the way Infinity
is stored in memory? If so, how can it still be that doing a | 0
operation causes it to return 0
whereas | 0
should not do anything?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
位运算符仅适用于整数。
Infinity
是浮点值,而不是整数。规范规定按位运算的所有操作数都会转换为整数(使用ToInt32 操作)在执行该操作之前。
ToInt32 操作表示:
Bitwise operators work on integers only.
Infinity
is a floating-point value, not an integer.The spec says that all operands of bitwise operations are converted to integers (using the ToInt32 operation) before performing the operation.
The ToInt32 operation says:
进行需要
NaN
和Infinity
整数的数学和其他运算通常是一个坏主意。您将如何设置/清除Infinity中的一点?实际上,按位运算仅针对整数定义 - 并且整数没有
NaN
或Infinity
。Doing math and other operations that expect integers with
NaN
andInfinity
is usually a bad idea. How would you set/clear a bit from Infinity?Actually, bit-wise operations are only defined for integers - and integers do not have
NaN
orInfinity
.