JavaScript Math(算數(shù))
Math(算數(shù))對(duì)象的作用是:執(zhí)行常見(jiàn)的算數(shù)任務(wù)。
在線(xiàn)實(shí)例
round()
如何使用 round()。
實(shí)例
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> </head> <body> <p id="demo">單擊按鈕舍入與“2.5”最接近的整數(shù)</p> <button onclick="myFunction()">點(diǎn)我</button> <script> function myFunction(){ document.getElementById("demo").innerHTML=Math.round(2.5); } </script> </body> </html>
運(yùn)行實(shí)例 ?
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線(xiàn)實(shí)例
random()
如何使用 random() 來(lái)返回 0 到 1 之間的隨機(jī)數(shù)。
實(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>
運(yùn)行實(shí)例 ?
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線(xiàn)實(shí)例
max()
如何使用 max() 來(lái)返回兩個(gè)給定的數(shù)中的較大的數(shù)。(在 ECMASCript v3 之前,該方法只有兩個(gè)參數(shù)。)
實(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>
運(yùn)行實(shí)例 ?
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線(xiàn)實(shí)例
min()
如何使用 min() 來(lái)返回兩個(gè)給定的數(shù)中的較小的數(shù)。(在 ECMASCript v3 之前,該方法只有兩個(gè)參數(shù)。)
實(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>
運(yùn)行實(shí)例 ?
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線(xiàn)實(shí)例
完整的 Math 對(duì)象參考手冊(cè)
我們提供 JavaScript Math 對(duì)象的參考手冊(cè),其中包括所有可用于算術(shù)對(duì)象的屬性和方法。
該手冊(cè)包含了對(duì)每個(gè)屬性和方法的詳細(xì)描述以及相關(guān)實(shí)例。
Math 對(duì)象
Math(算數(shù))對(duì)象的作用是:執(zhí)行普通的算數(shù)任務(wù)。
Math 對(duì)象提供多種算數(shù)值類(lèi)型和函數(shù)。無(wú)需在使用這個(gè)對(duì)象之前對(duì)它進(jìn)行定義。
使用Math的屬性/方法的語(yǔ)法:
var y=Math.sqrt(16);
注意: Math對(duì)象無(wú)需在使用這個(gè)對(duì)象之前對(duì)它進(jìn)行定義。
算數(shù)值
JavaScript 提供 8 種可被 Math 對(duì)象訪(fǎng)問(wèn)的算數(shù)值:
你可以參考如下Javascript常量使用方法:
Math.PI
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E
算數(shù)方法
除了可被 Math 對(duì)象訪(fǎng)問(wèn)的算數(shù)值以外,還有幾個(gè)函數(shù)(方法)可以使用。
下面的例子使用了 Math 對(duì)象的 round 方法對(duì)一個(gè)數(shù)進(jìn)行四舍五入。
上面的代碼輸出為:
下面的例子使用了 Math 對(duì)象的 random() 方法來(lái)返回一個(gè)介于 0 和 1 之間的隨機(jī)數(shù):
上面的代碼輸出為:
下面的例子使用了 Math 對(duì)象的 floor() 方法和 random() 來(lái)返回一個(gè)介于 0 和 11 之間的隨機(jī)數(shù):
上面的代碼輸出為: