為什么不帶參數(shù)的 Math.max() 返回-Infinity
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,接下來,我們來看看為什么會這樣。
1.一個(gè)數(shù)組中的最大值
在探討這個(gè)問題之前,我們先來 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)在,我們來看看有趣的事情,給定兩個(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.
沒毛病,我們繼續(xù)。
如果一個(gè)數(shù)組是空的,結(jié)果又會是怎么樣的, 我們動手試試:
- 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)于對實(shí)數(shù)的最大運(yùn)算,-Infinity稱為Identity元素
到這里本文就完啦,這里來個(gè)挑戰(zhàn):你能否編寫一個(gè)與Math.max()完全一樣的 sum(num1, num2, ..., numN)函數(shù),它的功能就是求所有元素的和,
Identity元素是什么,有懂的沒,歡迎留言補(bǔ)充一下知識點(diǎn)。
作者:Dmitri Pavlutin 譯者:前端小智 來源:Dmitri Pavlutin
原文:https://dmitripavlun.com/javscript-math-max-infinity/
本文轉(zhuǎn)載自微信公眾號「大遷世界」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請聯(lián)系大遷世界公眾號。