当前位置: 代码迷 >> 综合 >> js 利用Math.random生成随机整数
  详细解决方案

js 利用Math.random生成随机整数

热度:53   发布时间:2023-10-11 17:13:18.0

Math.random() 方法能够生成0~1之间的小数,可能会返回0但永远也不会是1。

在实际开发需求中,需要生成0到某个数之间的随机整数:

Math.floor(Math.random()*10)

结合Math.floor()向下取整,能给我们随机生成0-9之间的整数。

但是请注意,上面只能生成0到某个数之间的随机数,但我们可以通过下面这个公式得到任何minmax之间随机数:

公式:Math.floor(Math.random()*(max-min+1))+min

如:Math.floor(Math.random()*(15-0+1))+0  //随机获取0-15之间的随机整数(包括0和15)

 

  相关解决方案