JavaScript 的 Math 物件提供 max 函式,用來取得一組數字中的最大值。最常見的用法就是比較兩個數字。
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to return the highest number of 5 and 10.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = Math.max(5, 10);
}
</script>
</body>
</html>
按下按鈕後輸出:10
Math.max 不限於兩個參數,可以一次比較多個:
Math.max(3, 17, 8, 42); // 42
若數字放在陣列裡,需要用展開運算子攤平:
var nums = [3, 17, 8, 42]; Math.max.apply(null, nums); // 舊寫法 Math.max(...nums); // ES6 寫法,皆為 42
要搭配 Math.min 求最小值時邏輯完全對稱。另外注意:傳入任何非數字(包含 undefined)會得到 NaN,而空參數呼叫 Math.max() 會回傳 -Infinity,這兩個邊界行為在寫通用函式時值得留意。