使用js Math.random()函數產生n到m間的隨機數字

來源:互聯網
上載者:User

標籤:and   需要   mat   數字   返回   隨機   rand   驗證   不包含   

本文講解如何使用js產生n到m間的隨機數字,主要目的是為後期的js產生驗證碼做準備。

Math.random()函數返回0和1之間的偽隨機數,可能為0,但總是小於1,[0,1)

產生n-m,包含n但不包含m的整數:

第一步算出 m-n的值,假設等於w

第二步Math.random()*w

第三步Math.random()*w+n

第四步parseInt(Math.random()*w+n, 10)

產生n-m,不包含n但包含m的整數:?

第一步算出 m-n的值,假設等於w

第二步Math.random()*w

第三步Math.random()*w+n

第四步Math.floor(Math.random()*w+n) + 1

產生n-m,不包含n和m的整數:

第一步算出 m-n-2的值,假設等於w

第二步Math.random()*w

第三步Math.random()*w+n +1

第四步Math.round(Math.random()*w+n+1) 或者 Math.ceil(Math.random()*w+n+1)

產生n-m,包含n和m的隨機數:

第一步算出 m-n的值,假設等於w

第二步Math.random()*w

第三步Math.random()*w+n

第四步Math.round(Math.random()*w+n) 或者 Math.ceil(Math.random()*w+n)

例子:

  產生800-1500的隨機整數,包含800但不包含1500

 

複製代碼代碼如下:
1500-800 = 700
Math.random()*700
var num = Math.random()*700 + 800;
num = parseInt(num, 10);


只需要簡單的四步就可以完成。

補充:

 

  Math.ceil() 返回大於等於數字參數的最小整數(取整函數),對數字進行上舍入

  Math.floor() 返回小於等於數字參數的最大整數,對數字進行下舍入

  Math.round() 返回數字最接近的整數,四捨五入

使用js Math.random()函數產生n到m間的隨機數字

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.