js指定范围随机整数

时间:2023-07-15 16:30:44

js获取指定范围内随机整数,例如 6-10 (m-n)

计算公式:

Math.floor(Math.random()*(n-m))+m
// 6-10随机数,用循环得出一组测试随机数
var str = ""
for(let i=0; i<30; i++){
let num = Math.floor(Math.random()*5)+6
str += num+"-";
}
console.log(str);

如果有要求首尾m、n是否包含,如求 6-10随机整数(不包含6),实际上按上面公式也就是7-10,灵活处理一下就行。