JavaScript Math(算數(shù))對象
Math(算數(shù))對象的作用是:執(zhí)行常見的算數(shù)任務。
實例
Math 對象
Math(算數(shù))對象的作用是:執(zhí)行普通的算數(shù)任務。
Math 對象提供多種算數(shù)值類型和函數(shù)。無需在使用這個對象之前對它進行定義。
算數(shù)值
JavaScript 提供 8 種可被 Math 對象訪問的算數(shù)值:
- 常數(shù)
- 圓周率
- 2 的平方根
- 1/2 的平方根
- 2 的自然對數(shù)
- 10 的自然對數(shù)
- 以 2 為底的 e 的對數(shù)
- 以 10 為底的 e 的對數(shù)
這是在 Javascript 中使用這些值的方法:(與上面的算數(shù)值一一對應)
- Math.E
- Math.PI
- Math.SQRT2
- Math.SQRT1_2
- Math.LN2
- Math.LN10
- Math.LOG2E
- Math.LOG10E
算數(shù)方法
除了可被 Math 對象訪問的算數(shù)值以外,還有幾個函數(shù)(方法)可以使用。
函數(shù)(方法)實例:
下面的例子使用了 Math 對象的 round 方法對一個數(shù)進行四舍五入。
document.write(Math.round(4.7)
)
上面的代碼輸出為:
5
下面的例子使用了 Math 對象的 random() 方法來返回一個介于 0 和 1 之間的隨機數(shù):
document.write(Math.random()
)
上面的代碼輸出為:
0.9370844220218102
下面的例子使用了 Math 對象的 floor() 方法和 random() 來返回一個介于 0 和 10 之間的隨機數(shù):
document.write(Math.floor(Math.random()*11)
)
上面的代碼輸出為:
3