记一次有趣的发现--JavaScript中/0操作不被视为异常,弹出Infinity

411 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

代码:

<script type="text/javascript">
    let a = -10;
    let b = 0;

    try {
        let c = a/b;
        //当除数为0的时候,计算结果就是Infinity。
        alert(c);
    }catch (e){
        alert(e);
    }finally {
        alert("end")
    }

</script>

在这里插入图片描述 与意想的弹出报错信息相悖 又alert(c)后 在这里插入图片描述 度娘后才知道,/0操作在JS里并不被视为异常,

当除数为0的时候,计算结果就是Infinity。
例如 
5/0 = Infinity
5/Infinity = 0

JavaScript | Infinity Property The infinity property in JavaScript is much like the concept of infinity in mathematics where it is used to represent a number that is beyond our knowledge or one which cannot be expressed. JavaScript中的infinity属性与数学中的infinity概念非常相似,其中的infinity属性用于表示我们无法理解的数字或无法表达的数字。

除于大于1的数是分裂变小,除于小于1的数是聚合变大, 那么, 除于无限大,被除数就变得无限小; 除于无限小(0),被除数就变得无限大;

Java本身是强类型语言,作者比较理性,认为/0报错是严格遵守数学定义; JS则是弱类型语言,把/0这种还不能解释清楚地结果单独设置为一种类型属性,显得作者更为开放,把更多的遐想空间留给我们,毕竟人类现在对于宇宙的了解还是少之甚少

The above number seems extremely large, doesn't it? However, if you look at 1e+219 and compare it with the infinity number 3.4576917263943217389012348562315E+1203 it seems extremely small! You can imagine how huge the limit of the floating-point representation is by comparing a huge number that you can imagine or think to the actual limit which is even beyond your imagination! 上述数字似乎很大,不是吗? 但是,如果您查看1e + 219并将其与无穷大数3.4576917263943217389012348562315E + 1203进行比较,则看起来非常小! 通过将您可以想象或想到的巨大数字与甚至超出您的想象力的实际极限进行比较,您可以想象到浮点表示的极限有多大!

www.includehelp.com/Infinity Pr…