有没有办法用JavaScript生成指定范围内的随机数?
例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。
有没有办法用JavaScript生成指定范围内的随机数?
例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。
当前回答
ES6/Arrow函数版本基于Francis的代码(即顶级答案):
const randomIntFromInterval = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
其他回答
这已经晚了九年,但randojs.com让这成为了一个简单的一行:
rando(1, 6)
您只需要将其添加到html文档的头部,就可以轻松地使用随机性做任何事情。数组中的随机值、随机jquery元素、对象中的随机财产,甚至在需要时防止重复。
<script src="https://randojs.com/1.0.0.js"></script>
或者,在Undercore
_.random(min, max)
var x = 6; // can be any number
var rand = Math.floor(Math.random()*x) + 1;
如果您想覆盖负数和正数,并确保其安全,请使用以下方法:
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 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