JavaScript Math(算數(shù)) 對(duì)象
JavaScript?Math(算數(shù))?對(duì)象
Math(算數(shù))對(duì)象的作用是:執(zhí)行常見的算數(shù)任務(wù)。
如何使用 round():
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> </head> <body> <p id="demo">單擊按鈕舍入與“9.5”最接近的整數(shù)</p> <button onclick="myFunction()">點(diǎn)我</button> <script> function myFunction(){ document.getElementById("demo").innerHTML=Math.round(9.5); } </script> </body> </html>
如何使用 random() 來返回 0 到 1 之間的隨機(jī)數(shù):
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> </head> <body> <p id="demo">點(diǎn)擊按鈕顯示一個(gè)隨機(jī)數(shù)</p> <button onclick="myFunction()">點(diǎn)我</button> <script> function myFunction(){ document.getElementById("demo").innerHTML=Math.random(); } </script> </body> </html>
如何使用 max() 來返回兩個(gè)給定的數(shù)中的較大的數(shù)。(在 ECMASCript v3 之前,該方法只有兩個(gè)參數(shù)。):
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> </head> <body> <p id="demo">單擊按鈕返回5到10之間的最大值。</p> <button onclick="myFunction()">點(diǎn)我</button> <script> function myFunction(){ document.getElementById("demo").innerHTML=Math.max(5,10); } </script> </body> </html>
如何使用 min() 來返回兩個(gè)給定的數(shù)中的較小的數(shù)。(在 ECMASCript v3 之前,該方法只有兩個(gè)參數(shù)。)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> </head> <body> <p id="demo">單擊按鈕返回5到10之間最小的值。</p> <button onclick="myFunction()">點(diǎn)我</button> <script> function myFunction(){ document.getElementById("demo").innerHTML=Math.min(5,10); } </script> </body> </html>
Math 對(duì)象
Math(算數(shù))對(duì)象的作用是:執(zhí)行普通的算數(shù)任務(wù)。
Math 對(duì)象提供多種算數(shù)值類型和函數(shù)。無需在使用這個(gè)對(duì)象之前對(duì)它進(jìn)行定義。
使用Math的屬性/方法的語法:
var x=Math.PI;
var y=Math.sqrt(16);
注意:?Math對(duì)象無需在使用這個(gè)對(duì)象之前對(duì)它進(jìn)行定義。
算數(shù)值
JavaScript 提供 8 種可被 Math 對(duì)象訪問的算數(shù)值:
你可以參考如下Javascript常量使用方法:
Math.E
Math.PI
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E
算數(shù)方法
除了可被 Math 對(duì)象訪問的算數(shù)值以外,還有幾個(gè)函數(shù)(方法)可以使用。
下面的例子使用了 Math 對(duì)象的 round 方法對(duì)一個(gè)數(shù)進(jìn)行四舍五入。
document.write(Math.round(4.7));
上面的代碼輸出為:
5
下面的例子使用了 Math 對(duì)象的 random() 方法來返回一個(gè)介于 0 和 1 之間的隨機(jī)數(shù):
document.write(Math.random());
上面的代碼輸出為:
0.18346685613505542
下面的例子使用了 Math 對(duì)象的 floor() 方法和 random() 來返回一個(gè)介于 0 和 11 之間的隨機(jī)數(shù):
document.write(Math.floor(Math.random()*11));
上面的代碼輸出為:
9