DIV CSS 佈局教程網

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

Math.min 與 Math.max 完全對稱,只是取的是最小值。以下範例回傳 5 與 10 中較小者:

<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to return the lowest number of 5 and 10.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
  document.getElementById("demo").innerHTML = Math.min(5, 10);
}
</script>
</body>
</html>

輸出 5。

常用變化

Math.min(5, 10);          // 5
Math.min(-1, -5, 3);      // -5
Math.min(...[7, 2, 9]);   // 2,陣列要用展開語法
Math.min();               // Infinity,沒傳參數

// 加上下限夾擠(clamp),實作上非常常用
function clamp(value, min, max) {
  return Math.min(Math.max(value, min), max);
}
clamp(120, 0, 100);  // 100
clamp(-20, 0, 100);  // 0

clamp 這個小工具在處理捲動位置、拖曳邊界、音量與透明度設定時幾乎每次都會用到,值得直接收進工具函式庫。

最大值與最小值一次取

var data = [3, 1, 4, 1, 5, 9, 2, 6];

// 直觀但要走兩趟
Math.min(...data);
Math.max(...data);

// 一次走訪同時取得,資料量大時更合適
var result = data.reduce(function (acc, v) {
  if (v < acc.min) acc.min = v;
  if (v > acc.max) acc.max = v;
  return acc;
}, { min: Infinity, max: -Infinity });

和 Math.max 一樣,Math.min 會對參數做數字轉型,遇到非數字字串會得到 NaN;陣列過長時展開寫法也可能撞上參數數量上限,該改用 reduce 或迴圈。

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