2

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

 3 years ago
source link: https://segmentfault.com/a/1190000040525785
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

作者:Dmitri Pavlutin
译者:前端小智
来源:Dmitri Pavlutin

有梦想,有干货,微信搜索 【大迁世界】 关注这个在凌晨还在刷碗的刷碗智。

本文 GitHub https://github.com/qq449245884/xiaozhi 已收录,有一线大厂面试完整考点、资料以及我的系列文章。

Math.max() 是 JS 内置的方法,可以从传入的参数中,返回最大的一个。例如:

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

如果Math.max()只使用一个参数,结果是怎么样的?

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

正如预期的那样,一个数字的最大值就是它本身。

但是,如果调用不带参数 Math.max() 结果又是怎么样的呢?

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

不带参数的 Math.max() 返回的结果是 -Infinity,接下来,我们来看看为什么会这样。

一个数组中的最大值

在探讨这个问题之前,我们先来 Math.max()是如何从数组中得到最大值的。

Math.max(num1, num2, ..., numN)接受多个数字参数,并返回它们的最大数量。

如果想从数组中获取最大值,我们可以使用展开运算符:

const numbers1 = [1, 2, 3];

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

2. 两个数组中的最大值

现在,我们来看看有趣的事情,给定两个数组,我们先确定每个数组中的最大值,然后在从获取这两个最大值在确定出其中的最大值。

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

数组 [1, 2, 3] 最大值是 3,数组 [0, 6]大最值是 6,最后 3 和 6 的最大值是 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

现在,当第一个数组为空时,上面的最大值也是 6

这里比较有趣的是Math.max(...numbers1)的返回值,当numbers1数组为空时,这与调用不带参数的Math.max()相同,结果是 -Infinity

所以 Math.max(max1,max2) 等价于 Math.max(-Infinity, 6),结果为6。

现在就知道为什么Math.max()在不带参数的情况下调用时返回-Infinity:这是在一个空集合上定义max函数的一种方式。

这与加法类似,max的-Infinity和加法的0是一样的。

Math.min()也具有相同的行为-当不带参数调用时,它将返回Infinity

关于对实数的最大运算,-Infinity称为Identity元素

到这里本文就完啦,这里来个挑战:你能否编写一个与Math.max()完全一样的 sum(num1, num2, ..., numN)函数,它的功能就是求所有元素的和,

Identity元素是什么,有懂的没,欢迎留言补充一下知识点。


代码部署后可能存在的BUG没法实时知道,事后为了解决这些BUG,花了大量的时间进行log 调试,这边顺便给大家推荐一个好用的BUG监控工具 Fundebug

原文:https://dmitripavlun.com/javs...

有梦想,有干货,微信搜索 【大迁世界】 关注这个在凌晨还在刷碗的刷碗智。

本文 GitHub https://github.com/qq44924588... 已收录,有一线大厂面试完整考点、资料以及我的系列文章。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK