溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Math方法怎么在JavaScript中使用

發(fā)布時間:2021-01-06 16:22:23 來源:億速云 閱讀:130 作者:Leah 欄目:web開發(fā)

這篇文章將為大家詳細講解有關(guān)Math方法怎么在JavaScript中使用,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

1.min()和max()方法

Math.min()用于確定一組數(shù)值中的最小值。Math.max()用于確定一組數(shù)值中的最大值。

alert(Math.min(2,4,3,6,3,8,0,1,3));              //最小值
alert(Math.max(4,7,8,3,1,9,6,0,3,2));         //最大值

2.舍入方法

Math.ceil()執(zhí)行向上舍入,即它總是將數(shù)值向上舍入為最接近的整數(shù);

Math.floor()執(zhí)行向下舍入,即它總是將數(shù)值向下舍入為最接近的整數(shù);

Math.round()執(zhí)行標準舍入,即它總是將數(shù)值四舍五入為最接近的整數(shù);

例如:

alert(Math.ceil(25.9));                   //26
alert(Math.ceil(25.5));                   //26
alert(Math.ceil(25.1));                   //26
alert(Math.floor(25.9));                  //25
alert(Math.floor(25.5));                  //25
alert(Math.floor(25.1));                  //25
alert(Math.round(25.9));                     //26
alert(Math.round(25.5));                     //26
alert(Math.round(25.1));                     //25

3.random()方法

Math.random()方法返回介于0到1之間一個隨機數(shù),不包括0和1。如果想大于這個范圍的話,可以套用一下公式:

值 = Math.floor(Math.random() * 總數(shù) + 第一個值)

例如:

alert(Math.floor(Math.random() * 10 + 1));        //隨機產(chǎn)生1-10之間的任意數(shù)

for (var i = 0; i<10;i ++) {
    document.write(Math.floor(Math.random() * 10 + 5));       //5-14之間的任意數(shù)
    document.write('<br />');
}

為了更加方便的傳遞想要范圍,可以寫成函數(shù):

function selectFrom(lower, upper) {
    var sum = upper - lower + 1;                      //總數(shù)-第一個數(shù)+1
    return Math.floor(Math.random() * sum + lower);
}
for (var i=0 ;i<10;i++) {
    document.write(selectFrom(5,10));                 //直接傳遞范圍即可
    document.write('<br />');
}

4.其它方法

如下表格:

以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持億速云!

  法

  明

Math.abs(num)

返回num的絕對值

Math.exp(num)

返回Math.E的num次冪

Math.log(num)

返回num的自然對數(shù)

Math.pow(num,power)

返回num的power次冪

Math.sqrt(num)

返回num的平方根

Math.acos(x)

返回x的反余弦值

Math.asin(x)

返回x的反正弦值

Math.atan(x)

返回x的反正切值

Math.atan2(y,x)

返回y/x的反正切值

Math.cos(x)

返回x的余弦值

Math.sin(x)

返回x的正弦值

Math.tan(x)

返回x的正切值

關(guān)于Math方法怎么在JavaScript中使用就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI