Math.random()
方法能够生成0~1之间的小数,可能会返回0但永远也不会是1。
在实际开发需求中,需要生成0到某个数之间的随机整数:
Math.floor(Math.random() * 10 )
结合Math.floor()
向下取整,能给我们随机生成0-9
之间的整数。
但是请注意,上面只能生成0到某个数之间的随机数,但我们可以通过下面这个公式得到任何min
和max
之间随机数:
//公式
Math.floor(Math.random() * (max - min + 1)) + min
//实例:随机生成5(包含)到15(包含)范围随机整数
Math.floor(Math.random() * (15 - 5 + 1)) + 5
网友评论