有没有办法用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
其他回答
如果您想覆盖负数和正数,并确保其安全,请使用以下方法:
JS解决方案:
function generateRangom(low, up) {
const u = Math.max(low, up);
const l = Math.min(low, up);
const diff = u - l;
const r = Math.floor(Math.random() * (diff + 1)); //'+1' because Math.random() returns 0..0.99, it does not include 'diff' value, so we do +1, so 'diff + 1' won't be included, but just 'diff' value will be.
return l + r; //add the random number that was selected within distance between low and up to the lower limit.
}
Java解决方案:
public static int generateRandom(int low, int up) {
int l = Math.min(low, up);
int u = Math.max(low, up);
int diff = u - l;
int r = (int) Math.floor(Math.random() * (diff + 1)); // '+1' because Math.random() returns 0..0.99, it does not include 'diff' value, so we do +1, so 'diff + 1' won't be included, but just 'diff' value will be.
return l + r;//add the random number that was selected within distance between low and up to the lower limit.
}
我写了一个更灵活的函数,它可以给你随机数,而不仅仅是整数。
function rand(min,max,interval)
{
if (typeof(interval)==='undefined') interval = 1;
var r = Math.floor(Math.random()*(max-min+interval)/interval);
return r*interval+min;
}
var a = rand(0,10); //can be 0, 1, 2 (...) 9, 10
var b = rand(4,6,0.1); //can be 4.0, 4.1, 4.2 (...) 5.9, 6.0
固定版本。
实例
返回1到10之间的随机数:
Math.floor((Math.random() * 10) + 1);
结果可能是:3.
试试看:这里
--
或使用lodash/descore:
_.随机(最小值,最大值)
文件:-罗达什-不受欢迎的
或者,在Undercore
_.random(min, max)
尝试使用:
函数随机(最小值,最大值){return Math.round((Math.random()*(Math.abs(max-min)))+min);}console.log(随机(1,6));