JS生成随机数
首先我们可以直接使用Math.random()方法,生成的是一个大于0小于1的浮点数。
console.log(Math.random())//0-1
那么我们就可以根据它来推导出以下的结论:
console.log(Math.random()*50)//0-50
console.log(Math.random()*50+50)//50-100
console.log(Math.random()*10+80)//80-90
console.log(Math.random()*180+60)//60-240
总结一下就是:
要想生成min-max之间的随机数,可以用以下公式来输出:
Math.random()*(max-min)+min;
以上是生成随机数的一些推论,那么如果我们想生成min-max之间的整数该怎么办呢?下面是我总结的一些方法:
1.可以将随机数四舍五入:
console.log(Math.round(1.44))//四舍五入
2.可以采用进一法:
console.log(Math.floor(1.44))//进一法
3.当然也可以采用去尾法,下面是去尾法的两种表达形式:
console.log(Math.ceil(1.44))//去尾法
console.log(~~(1.6))//去尾法
以上就是通过内置函数来实现随机数的所有结论了,接下来给大家介绍另一种方法:
基于时间,亦可以产生随机数。
代码如下:
:var now=new Date();
var number = now.getSeconds();
这将产生一个基于目前时间的0到59的整数。
var now=new Date();
var number = now.getSeconds()%43;
这将产生一个基于目前时间的0到42的整数。
以上就是我总结的两种js生成随机数的方法。