1. 程式人生 > >JavaScript中獲取隨機數

JavaScript中獲取隨機數

js生成隨機數

1. 先說幾個Math函式

Math.floor() 向下取整

Math.ceil() 向上取整

Math.parseInt() 截去小數,只保留整數位

Math.random() 獲取0-1之間的隨機數

Math.round()  四捨五入

 

2. 獲取偽隨機數

獲取0-9的隨機數 Math.parseInt(Math.random() * 10)

獲取0-N的隨機數 Math.parseInt(Math.random() * N)

獲取1-10的隨機數 Math.parseInt(Math.random() * 10 + 1)

獲取1-N的隨機數 Math.parseInt(Math.random() * N + 1)

獲取0-N的隨機數 Math.parseInt(Math.random() * (N + 1))

獲取N-M的隨機數 Math.parseInt(Math.random() * (M - N + 1) +  N)

 

用floor()寫法和parseInt()一樣,用ceil()則再是否+1上會有區別。