有没有办法用JavaScript生成指定范围内的随机数?
例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。
有没有办法用JavaScript生成指定范围内的随机数?
例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。
当前回答
jsfiddle:https://jsfiddle.net/cyGwf/477/
随机整数:要获得最小值和最大值之间的随机整数,请使用以下代码
function getRandomInteger(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
随机浮点数:要获得最小值和最大值之间的随机浮点数,请使用以下代码
function getRandomFloat(min, max) {
return Math.random() * (max - min) + min;
}
参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
其他回答
或者,在Undercore
_.random(min, max)
对于大数字。
var min_num = 900;
var max_num = 1000;
while(true){
let num_random = Math.random()* max_num;
console.log('input : '+num_random);
if(num_random >= min_num){
console.log(Math.floor(num_random));
break;
} else {
console.log(':::'+Math.floor(num_random));
}
}
jsfiddle:https://jsfiddle.net/cyGwf/477/
随机整数:要获得最小值和最大值之间的随机整数,请使用以下代码
function getRandomInteger(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
随机浮点数:要获得最小值和最大值之间的随机浮点数,请使用以下代码
function getRandomFloat(min, max) {
return Math.random() * (max - min) + min;
}
参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
尝试使用:
函数随机(最小值,最大值){return Math.round((Math.random()*(Math.abs(max-min)))+min);}console.log(随机(1,6));
获取0到400之间的随机整数
let rand=数学舍入(Math.random()*400)document.write(兰特)
获取200到1500之间的随机整数
让范围={min:200,max:1500}设delta=范围.max-范围.minconst rand=数学舍入(range.min+Math.random()*delta)document.write(兰特)
使用函数
函数randBetween(最小值,最大值){设delta=最大值-最小值return Math.round(min+Math.random()*delta)}document.write(randBetween(10,15));
//JavaScript ES6箭头函数常量randBetween=(最小值,最大值)=>{设delta=最大值-最小值return Math.round(min+Math.random()*delta)}document.write(randBetween(10,20))