Math.min() 为什么比 Math.max() 大?

考虑如下代码:

var min = Math.min();
var max = Math.max();
console.log(min < max);

按照常规思路,这段代码应该输出 true,毕竟最小值应该小于最大值。但是当我们运行这段代码时,却神奇的输出了 false

为什么会这样呢?

还得去查查 MDN 的相关文档。

The Math.min() function returns the smallest of zero or more numbers.

Math.min 的参数是 0 个或者多个。如果是多个参数很容易理解,返回参数中最小的。

如果是 0 个参数呢?文档中写到:

If no arguments are given, the result is Infinity.

If at least one of arguments cannot be converted to a number, the
result is NaN.

如果没有参数,则返回 InfinityInfinity 是什么呢?Infinity 是 javascript 中全局对象的一个属性,在浏览器环境中就是 window 对象的一个属性,表示无穷大。

Math.max() 没有传递参数时返回的是 -Infinity

因此 Math.min() 要比 Math.max() 大。

继续阅读:为什么 Math.min() 比 Math.max() 大?(续)

    原文作者:justjavac
    原文地址: https://www.jianshu.com/p/ae5b0cc2a04f
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞