日期:2014-05-16  浏览次数:20312 次

js生成随机数的方法

?

1、JavaScript Math.random()内置函数

?

random函数返回值

?

返回0和1之间的伪随机数,可能为0,但总是小于1,[0,1)

?


2、Math.ceil(n); 返回大于等于n的最小整数。


用Math.ceil(Math.random()*10);时,主要获取1到10的随机整数,取0的几率极小。

?


3、Math.round(n); 返回n四舍五入后整数的值。


用Math.round(Math.random());可均衡获取0到1的随机整数。
用Math.round(Math.random()*10);时,可基本均衡获取0到10的随机整数,其中获取最小值0和最大值10

的几率少一半。

?


4、Math.floor(n); 返回小于等于n的最大整数。


用Math.floor(Math.random()*10);时,可均衡获取0到9的随机整数。

?

?

5、基于时间,亦可以产生随机数

?

var now=new Date();
var number = now.getSeconds(); //这将产生一个基于目前时间的0到59的整数。

var now=new Date();
var number = now.getSeconds()%43; //这将产生一个基于目前时间的0到42的整数。

?

参考资料:?? js如何生成随机数?? http://www.studyofnet.com/news/181.html