有没有办法用JavaScript生成指定范围内的随机数?
例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。
有没有办法用JavaScript生成指定范围内的随机数?
例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。
当前回答
这应该是有效的:
const getRandomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min
其他回答
或者,在Undercore
_.random(min, max)
此函数可以生成介于(包括)最小值和最大值之间的随机整数:
function randomNumber(min, max) {
if (min > max) {
let temp = max;
max = min;
min = temp;
}
if (min <= 0) {
return Math.floor(Math.random() * (max + Math.abs(min) + 1)) + min;
} else {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
}
例子:
randomNumber(-2, 3); // can be -2, -1, 0, 1, 2 and 3
randomNumber(-5, -2); // can be -5, -4, -3 and -2
randomNumber(0, 4); // can be 0, 1, 2, 3 and 4
randomNumber(4, 0); // can be 0, 1, 2, 3 and 4
如果起始数字是1,如示例(1-6)所示,则可以使用Math.ceil()方法代替Math.floor()。
Math.ceil(Math.random() * 6)
而不是
Math.floor(Math.random() * 6) + 1
我们不要忘记其他有用的数学方法。
重要的
The following code works only if the minimum value is `1`. It does not work for minimum values other than `1`.如果你想得到一个介于1(且只有1)和6之间的随机整数,你可以计算:
const rndInt=数学地板(Math.random()*6)+1控制台日志(rndInt)
哪里:
1是起始编号6是可能结果的数量(1+start(6)-end(1))
对于大数字。
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));
}
}