问题描述
在我看来,代码
console.log(1 / 0)
应该返回 NaN
,但它返回的是 Infinity
.但是这段代码:
should return NaN
, but instead it returns Infinity
. However this code:
console.log(0 / 0)
确实返回NaN
.有人可以帮我理解这个功能的原因吗?在 x/0
where x !== 0
does return NaN
. Can someone help me to understand the reasoning for this functionality? Not only does it seem to be inconsistent, it also seems to be wrong, in the case of x / 0
where x !== 0
推荐答案
因为浮点数是这样定义的(更普遍的不仅仅是 Javascript).例如:
Because that's how floating-point is defined (more generally than just Javascript). See for example:
粗略地说,您可以将 1/0 视为 1/x 的极限,因为 x 趋于零(从右侧开始).而 0/0 根本没有合理的解释,因此是 NaN.
Crudely speaking, you could think of 1/0 as the limit of 1/x as x tends to zero (from the right). And 0/0 has no reasonable interpretation at all, hence NaN.
这篇关于在 JavaScript 中,为什么零除以零返回 NaN,而任何其他除以零返回 Infinity?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!