Math.round和Math.random取得随机数

Math.round(Math.random()*99)有时结果会是9,我的用意是取得固定位数的随机数。那么Math.round(Math.random()*9999)有可能是3位也会是4位,怎么获得固定长度呢。

那你要去的随机数的范围是 多少到多少呢?
比如 :你需要去的随机数为0-9,每个概率为1/10 就这样写
Math.round(Math.random()*9)

如果你是想要65-70,每个概率为1/6,(65,66,67,68,69,70一共6个数)
就这样写
Math.round(Math.random()*5)+65
如果你需要 1/10000 的概率的话就是你上面的那种
Math.round(Math.random()*9999)

而你想要的是1/10000的概率,但你需要的数字要小于1000(小于3位数字)
num=Math.round(Math.random()*9999)

循环开始 1=1 (代码忘记了不写了你自己写无限循环)

if(num>1000 ){
num=Math.round(Math.random()*9999)
}else{
退出循环命令

}
结束循环
这样就可以获得低于4位的数字了 如果要求 需要几位数字可以再 if条件里面自己加 条件
比如 NUM>1000 and num < 99
他就获取3数字(100-999)
温馨提示:答案为网友推荐,仅供参考
第1个回答  2018-05-14
function randomcolor()
{
var colorvalue=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"],
colorprefix="#";
for(var i=1;i <= 6; i++){
index=Math.round(Math.random()*colorvalue.length);
colorprefix+=colorvalue[index];
}
return colorprefix;
}
var test=randomcolor();
alert(test);
如上 参考生成六位随机颜色的代码 colorvalue.length也可以替换为15
此代码生成的是colorvalue组里随机六位数
相似回答