Why check for !isNaN() after isFinite()?

后端 未结 5 927
你的背包
你的背包 2021-02-01 17:04

I came across the goog.math.isFiniteNumber function in the Google Closure Library. What it does is checking whether a given number is both finite and not NaN<

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-01 17:47

    you might reason out [Why?] after reading this:

    NaN doesn't check if the passed value is infinite or not - it checks if the input val evaluates into a "Type: Number" end-result. Because isNaN(string) is accepted, so the: isNaN("3.14") //false (which means true, the given token is duck converted into a type Number successfully )

    You may understand that the input value may happen to be an unresolved brute number, even a math operation as simple as: (x/y); which in turn might yield a (+/-infinity) number.

    Here x=1, y=0; meaning (1/0).Then isNaN(x/y) will first evaluate to isNaN(1/0); then to isNaN(infinity) //false. Since (1/0)=infinity is of type: "number" ie typeof(1/0) //"number" isNaN should and will return false.

    You don't want to put "infinity" where an end result number is expected.

提交回复
热议问题