Math.random()

來源:互聯網
上載者:User

標籤:

1.Math.random() 隨機函數

Math.random()是令系統隨機選取大於等於 0.0 且小於 1.0 的隨機數

alert(Math.random())取值在[0,1)

 

2.Math.round(數字) 四捨五入

alert(Math.round(3.2)) 彈出3

alert(Math.round(Math.random()))  彈出0或者1  // 0/1

 

0~10        alert(Math.round(Math.random()*10))  彈出0~10   

5~10        alert(Math.round(Math.random()*5+5))  彈出5~10  

10~20      alert(Math.round(Math.random()*10+10))  彈出10~20  

20~100    alert(Math.round(Math.random()*80+20))  彈出20~100

推理

x~y           alert(Math.round(Math.random()*(y-x)+x))  彈出x~y

0~x          alert(Math.round(Math.random()*x))             彈出x0~x

1~x           alert(Math.ceil(Math.random()*x))                彈出1~x

驗證

<script>
var x=42;
var y=45;
alert(Math.round(Math.random()*(y-x)+x))
</script>

彈出 42,43,44,45

Math.random()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.