为什么不带参数的 Math.max() 返回 -Infinity

Math.max()是内置的 JavaScript 函数,从给定的一组数字中返回最大值。

其语法如下:

Math.max(value1[, value2, ...])

例如,让我们从 1,2 以及 3 中找到最大的数字:

Math.max(1, 2, 3); // => 3

正如预期的那样,函数的返回值为 3。

当调用 Math.max()时只使用一个数字参数时:

Math.max(1); // => 1

显然,一个数字的最大值是其本身。

但如果调用 Math.max() 时不传递任何参数,那会发生什么?

Math.max(); // => -Infinity

乍看之下上述代码的执行结果似乎有点出人意料,在没有参数的情况下调用 Math.max() 会返回 -Infinity。让我们来看看为什么会发生这种情况,以及为什么要发生这种情况。

一个数组的最大值
如果要确定一个数组的最大数字,可以在数组上使用扩展运算符:

const numbers1 = [1, 2, 3];

Math.max(...numbers1); // => 3

两个数组的最大值
目前,让我们尝试从给定两个数字数组中,确定每个数组的最大数,然后确定这两个最大值中的最大值。

const numbers1 = [1, 2, 3];
const numbers2 = [0, 6];

const max1 = Math.max(...numbers1);
const max2 = Math.max(...numbers2);

max1; // 3
max2; // 6
Math.max(max1, max2); // => 6

如果其中一个数组为空,如何尝试确定最大数组呢?

const numbers1 = [];
const numbers2 = [0, 6];

const max1 = Math.max(...numbers1);
const max2 = Math.max(...numbers2);

max1; // -Infinity
max2; // 6
Math.max(max1, max2); // => 6

从上述代码可以看出,Math.max(...[]) 与不带参数的Math.max()结果一样,均为-Infinity

然后 Math.max(max1, max2)Math.max(-Infinity, 6),其结果为 6。

尾声
目前就很清楚为什么在不带参数的情况下Math.max()返回 -Infinity了,无论numbers2的最大值是多少,为了让空数组 numbers1(等同于不带参数的Math.max())的最大值小于numbers2 的最大值,numbers1 的最大值只能是负无穷,即-Infinity

同理,Math.min() return Infinity

也因此:

Math.min() > Math.max(); // => true

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
番茄那个小肥牛的头像 - 鹿快
评论 抢沙发

请登录后发表评论

    暂无评论内容