【转载】js生成某个范围的随机整数
原文地址:https://www.jianshu.com/p/755bc48467f1
原文重点:
1.min ≤ r ≤ max
function Random(min, max) { return Math.round(Math.random() * (max - min)) + min; }
2.min﹤r ≦ max
function Random(min, max) { return Math.ceil(Math.random() * (max - min)) + min; } function Random(min, max) { return Math.round(Math.random() * (max - min)) === 0? (min+1):Math.round(Math.random() * (max - min)) + min; }
3.min≦ r ﹤ max
function Random(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function Random(min, max) {
return Math.round(Math.random() * (max - min)) === max ? (max-1):Math.round(Math.random() * (max - min)) + min;
}
4.min﹤ r ﹤ max
function Random(min, max) {
return Math.floor(Math.random() * (max - min)) === min ? (min + 1) : Math.floor(Math.random() * (max - min)) + min;
}
function Random(min, max) {
return Math.floor(Math.random() * ((max-1) - (min+1))) + (min+1);相当于 min+1 ≤ r ≤ max - 1
}