Math.random( )方法

 Math.random( )可以产生一个0~1之间的随机数,可以利用它产生一个某一整数范围内的随机值。

值 = Math.floor( Math.random * 可能值的总数 + 第一个可能值)

 举个例子:返回一个1~10之间的随机整数

var num = Math.floor( Math.random() * 10 + 1);

 因为Math.random * 10 < 10,所以1<(Math.random*10 + 1)<11, 用Math.floor方法舍去小数部分,则可以得到1~10之间的整数(随机)。

可以通过一个函数计算可能值的总数,第一个可能的值

function selectFrom(lowerValue, upperValue) {
    var choices = upperValue - lowerValue + 1;
    return Math.floor(Math.random() * choices + lowerValue);
}
var num = selectFrom(2,10);
alert(num);

只要输入参数,就可以得到相应区间的随机值了。

 

posted on 2016-09-03 09:49  Meiis  阅读(725)  评论(0)    收藏  举报

导航