前言:
對象在JavaScript 中被稱爲引用類型的值。
Math 是引用類型的單體內置對象,Math對象提供了很多屬性和方法,用於輔助完成複雜的數學計算任務。
Math 對象方法
方法 | 描述 |
---|---|
Math.ceil(x) | 進行上舍入,即向上取整。 例:Math.ceil(25.9) //26 Math.ceil(25.1) //26 |
Math.floor(x) | 進行向下舍入,即向下取整。 例:Math.floor(25.9) //25 Math.floor(25.1) //25 |
Math.round(x) | 進行四捨五入(標準舍入)。 例:Math.floor(25.5) //26 Math.floor(25.1) //25 |
Math.random() | 返回 0 ~ 1 之間的隨機數,包含 0 不包含 1 |
random 方法
值 = Math.floor(Math.random() * 可能值的總數 + 第一個可能的值)
舉例: 生成 (1 ~ 10 之間的數值)
let num = Math.floor(Math.random() * 10 + 1);
生成[n,m]的隨機整數
函數功能:生成[n,m]的隨機整數。
// 包括 min ~ max 的數值
function selectFrom(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
console.log(selectFrom(2,6)); //包括 2 ~ 6 的數值