In JavaScript, why does zero divided by zero return NaN, but any other divided by zero return Infinity?

前端 未结 3 1106
清酒与你
清酒与你 2020-11-29 07:53

It seems to me that the code

console.log(1 / 0)

should return NaN, but instead it returns Infinity. However this

3条回答
  •  广开言路
    2020-11-29 08:40

    I realize this is old, but I think it's important to note that in JS there is also a -0 which is different than 0 or +0 which makes this feature of JS much more logical than at first glance.

    1 / 0 -> Infinity
    1 / -0 -> -Infinity 
    

    which logically makes sense since in calculus, the reason dividing by 0 is undefined is solely because the left limit goes to negative infinity and the right limit to positive infinity. Since the -0 and 0 are different objects in JS, it makes sense to apply the positive 0 to evaluate to positive Infinity and the negative 0 to evaluate to negative Infinity

    This logic does not apply to 0/0, which is indeterminate. Unlike with 1/0, we can get two results taking limits by this method with 0/0

    lim h->0(0/h) = 0
    lim h->0(h/0) = Infinity
    

    which of course is inconsistent, so it results in NaN

提交回复
热议问题