Math對象或者說是類型旗下?lián)碛泻芏嗥綍r常用的數學函數,雖然并不像Date和String那樣擁有類似于類和方法那樣的使用方式,不過并不妨礙您通過本文來輕松掌握JavaScript中的Math object數學對象^^
對于內置的Math數學常項和函數也有一些屬性和方法。 比方說, Math對象的 PI 屬性會有屬性值 pi (3.141...),你可以像這樣調用它:
Math.PI
同理,標準數學函數也是Math的方法。 這些包括三角函數,對數,指數,和其他函數。比方說你想使用三角函數 sin, 你可以這么寫:
Math.sin(1.56)
需要注意的是Math的所有三角函數參數都是弧度制。
和其他對象不同,你不能夠創(chuàng)建一個自己的Math對象。你只能使用內置的Math對象。
eg:
1.min( )和max( )
var value = [1,2,3,4,5,6,7,8];
var max = Math.max.apply(Math, values);
2.舍入方法
Math.ceil( ):向上舍入
Math.floor( ):向下舍入
Math.round( ):四舍五入
3.random( )
Math.random( )方法返回介于0和1之間的一個隨機數,不包括0和1
var num = Math.floor(Math.random()*10, + 1)//返回1-10之間的數
4.round()
如何使用 round()。
<html>
<body>
<script type="text/javascript">
document.write(Math.round(0.60) + "<br />")
document.write(Math.round(0.50) + "<br />")
document.write(Math.round(0.49) + "<br />")
document.write(Math.round(-4.40) + "<br />")
document.write(Math.round(-4.60))
</script>
</body>
</html>
5.random()
如何使用 random() 來返回 0 到 1 之間的隨機數。
<html>
<body>
<script type="text/javascript">
document.write(Math.random())
</script>
</body>
</html>