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上会有区别。

猜你喜欢

转载自www.cnblogs.com/lyhomepage/p/10266631.html