首发于代码之谜
Math.min() 为什么比 Math.max() 大?

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.

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

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

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

全文完。

--------------------------------

每周推送原创高质量文章,欢迎关注我的公众号

编辑于 2016-09-17 21:11