在我的程序中,我想生成仅包含数字(1 到 7)的 5 位随机数。
var randnum = Math.floor(Math.random() * (11111 - 77777 + 1)) + 11111;
使用上面的代码,我得到了 11111
和 77777
之间的号码。但是如何生成不包含 0,8,9
的数字呢?有没有默认的方法来生成这种数字?
最佳答案
您可以一次生成每个数字,将它们连接起来,然后 parseInt 以获得结果:
var str = '';
for (var i=0; i<5; i++) {
str += Math.floor(Math.random()*7) + 1;
}
var randnum = parseInt(str);
说明
Math.random()
返回 [0,1)
Math.random() * 7
返回 [0,7)
Math.floor(...)
返回 0,1,2,3,4,5,6
...+1
返回 1,2,3,4,5,6,7
关于javascript - 使用javascript中的特定数字生成随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19022480/