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