How do I check if a number evaluates to infinity?

前端 未结 7 798
孤城傲影
孤城傲影 2020-12-07 19:24

I have a series of Javascript calculations that (only under IE) show Infinity depending on user choices.

How does one stop the word Infinity appearing a

7条回答
  •  情歌与酒
    2020-12-07 20:22

    I've ran into a scenario that required me to check if the value is of the NaN or Infinity type but pass strings as valid results. Because many text strings will produce false-positive NaN, I've made a simple solution to circumvent that:

      const testInput = input => input + "" === "NaN" || input + "" === "Infinity";
    
    

    The above code converts values to strings and checks whether they are strictly equal to NaN or Infinity (you'll need to add another case for negative infinity).

    So:

    testInput(1/0); // true
    testInput(parseInt("String")); // true
    testInput("String"); // false
    

提交回复
热议问题