JavaScript中获取随机数

js生成随机数

1. 先说几个Math函数

Math.floor() 向下取整

Math.ceil() 向上取整

parseInt() 解析一个字符串,并返回一个整数

Math.random() 获取0-1之间的随机数

Math.round()  四舍五入

 

2. 获取伪随机数

获取0-9的随机数 parseInt(Math.random() * 10)

获取0-N的随机数 parseInt(Math.random() * N)

获取1-10的随机数 parseInt(Math.random() * 10 + 1)

获取1-N的随机数 parseInt(Math.random() * N + 1)

获取0-N的随机数 parseInt(Math.random() * (N + 1))

获取N-M的随机数 parseInt(Math.random() * (M - N + 1) +  N)

 

用floor()写法和parseInt()一样,用ceil()则再是否+1上会有区别。

posted @ 2019-01-14 14:39  天边飞来的鸟  阅读(6983)  评论(0编辑  收藏  举报