DIV CSS 佈局教程網

輕鬆掌握 JavaScript 中的 Math 數學對象
編輯:JavaScript基礎知識     

JavaScript 為內置的數學常量與函數提供了 Math 對象。比如 Math 對象的 PI 屬性就是圓周率 pi(3.141…),可以這樣調用:

 Math.PI 

同理,標準數學函數也是 Math 的方法,包括三角函數、對數、指數等。比如要用正弦函數 sin,可以這樣寫:

 Math.sin(1.56) 

需要注意的是,Math 的所有三角函數參數都是弧度制。此外,與其他對象不同,你不能創建自己的 Math 對象,只能使用內置的 Math 對象。

示例:

1. min() 和 max()

 var value = [1,2,3,4,5,6,7,8]; var max = Math.max.apply(Math, value); 

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() 的使用

 <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() 返回 0 到 1 之間的隨機數

 <html> <body> <script type="text/javascript"> document.write(Math.random()) </script> </body> </html> 
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved