生成不从零开始的范围内的随机整数

时间:2011-07-15 02:40:19

标签: javascript random

如何生成7到10之间的数字?到目前为止,我所知道的是在0-10的范围内产生:

Math.floor(Math.random()*11)

4 个答案:

答案 0 :(得分:62)

function getRandom(min, max) {
    return min + Math.floor(Math.random() * (max - min + 1));
}

for(var x = 0; x < 5; x++) {
    alert(getRandom(7, 10));
}

答案 1 :(得分:21)

Math.floor(7 + Math.random() * 4)将生成7到10之间的数字。

答案 2 :(得分:4)

请说出来:

Math.floor(Math.random()*4) + 7

这将从0-3生成一个随机数,然后再加7,得到7-10。

答案 3 :(得分:0)

7 + Math.floor(Math.random()*4)