Math 是 JavaScript 中處理數值運算的重要內建物件。它提供許多常用常數與方法,例如最大值、最小值、絕對值、取整、指數、三角函數與隨機數。
Math.max 與 Math.min 可用來取得一組數值中的最大值與最小值。
var max = Math.max(1, 2, 3);
var min = Math.min(1, 2, 3);Math.abs 會回傳數值的絕對值,不論輸入是正數或負數。
var value = Math.abs(-10);Math.ceil 會向上取整,Math.floor 會向下取整,Math.round 則會進行四捨五入。
Math.ceil(25.5);
Math.floor(25.5);
Math.round(25.5);Math.exp、Math.log、Math.pow 與 Math.sqrt 分別處理指數、自然對數、次方與平方根運算。
Math.exp(1);
Math.log(10);
Math.pow(2, 3);
Math.sqrt(16);Math 也提供常見三角函數,例如 sin、cos、tan、asin、acos、atan 與 atan2。這些方法常用於動畫、遊戲與幾何計算。
Math.random 會回傳一個大於或等於 0、且小於 1 的隨機數。若要取得指定範圍內的整數,可以搭配 Math.floor 使用。
function selectFrom(first, last) {
var choices = last - first + 1;
return Math.floor(Math.random() * choices + first);
}掌握 Math 物件的常用方法,可以讓數值處理更簡潔,也能減少自行實作時可能發生的錯誤。