Math.max()是 JS 內(nèi)置的方法,可以從傳入的參數(shù)中,返回最大的一個(gè)。例如:
Math.max(1,2,3); // =>3
如果Math.max()只使用一個(gè)參數(shù),結(jié)果是怎么樣的?
Math.max(1); // =>1
正如預(yù)期的那樣,一個(gè)數(shù)字的最大值就是它本身。
但是,如果調(diào)用不帶參數(shù)Math.max()結(jié)果又是怎么樣的呢?
Math.max(); // => -Infinity
不帶參數(shù)的Math.max()返回的結(jié)果是-Infinity,接下來(lái),我們來(lái)看看為什么會(huì)這樣。
一個(gè)數(shù)組中的最大值
在探討這個(gè)問(wèn)題之前,我們先來(lái)Math.max()是如何從數(shù)組中得到最大值的。
Math.max(num1, num2, ..., numN)接受多個(gè)數(shù)字參數(shù),并返回它們的最大數(shù)量。
如果想從數(shù)組中獲取最大值,我們可以使用展開運(yùn)算符:
const numbers1 = [1, 2, 3];
Math.max(...numbers1); // => 3
2. 兩個(gè)數(shù)組中的最大值
現(xiàn)在,我們來(lái)看看有趣的事情,給定兩個(gè)數(shù)組,我們先確定每個(gè)數(shù)組中的最大值,然后在從獲取這兩個(gè)最大值在確定出其中的最大值。
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
數(shù)組[1, 2, 3]最大值是 3,數(shù)組[0, 6]大最值是 6,最后 3 和 6 的最大值是 6.
沒(méi)毛病,我們繼續(xù)。
如果一個(gè)數(shù)組是空的,結(jié)果又會(huì)是怎么樣的, 我們動(dòng)手試試:
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
現(xiàn)在,當(dāng)?shù)谝粋€(gè)數(shù)組為空時(shí),上面的最大值也是6。
這里比較有趣的是Math.max(...numbers1)的返回值,當(dāng)numbers1數(shù)組為空時(shí),這與調(diào)用不帶參數(shù)的Math.max()相同,結(jié)果是-Infinity。
所以Math.max(max1,max2)?等價(jià)于Math.max(-Infinity, 6),結(jié)果為6。
現(xiàn)在就知道為什么Math.max()在不帶參數(shù)的情況下調(diào)用時(shí)返回-Infinity:這是在一個(gè)空集合上定義max函數(shù)的一種方式。
這與加法類似,max的-Infinity和加法的0是一樣的。
Math.min()也具有相同的行為-當(dāng)不帶參數(shù)調(diào)用時(shí),它將返回Infinity。
關(guān)于對(duì)實(shí)數(shù)的最大運(yùn)算,-Infinity稱為Identity元素
到這里本文就完啦,這里來(lái)個(gè)挑戰(zhàn):你能否編寫一個(gè)與Math.max()完全一樣的sum(num1, num2, ..., numN)函數(shù),它的功能就是求所有元素的和,