DIV CSS 佈局教程網

Math.max:取多個數字中的最大值
編輯:關於JavaScript     

Math.max 回傳參數中的最大值。以下範例比較 5 與 10:

<!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(5, 10);        // 10
Math.max(1, 9, 3, 7);   // 9,可傳任意多個參數
Math.max();             // -Infinity,沒傳參數時的結果
Math.max(-5, -2);       // -2,負數之間一樣有效

// 陣列要先用展開語法攤開
Math.max(...[4, 8, 15]);  // 15

Math.max(...arr) 有參數數量上限。陣列很長時(實務上約十萬筆以上,依引擎而異)會出 RangeError。資料量大時請改用一次遍歷:

function maxOf(arr) {
  return arr.reduce(function (m, v) { return v > m ? v : m; }, -Infinity);
}

兩個容易誤判的細節

第一,Math.max 會先做數字轉型,所以 Math.max("5", 10) 得到 10,而 Math.max("abc", 10) 得到 NaN。傳入前最好確定型別。

第二,Math.max() 不傳參數回傳 -Infinity、Math.min() 回傳 Infinity,這個設計其實很合理(它是單位元),但在找不到最大值時若直接顯示結果,畫面上會出現奇怪的 -Infinity,記得處理。

另外,若你要同時取最大與最小,別呼叫兩次(會走訪兩輪),用一次 reduce 同時維護兩個變數會更有效率。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved