如何在JavaScript中的两个指定变量之间生成随机整数,例如x=4和y=8将输出4、5、6、7、8中的任意一个?
当前回答
所有这些解决方案都使用了太多的火力。您只需要调用一个函数:Math.random();
Math.random() * max | 0;
这将返回一个介于0(包含)和max(非包含)之间的随机整数。
其他回答
这是我用来生成随机数的方法。
function random(min,max) {
return Math.floor((Math.random())*(max-min+1))+min;
}
Math.random()返回一个介于0(含)和1(不含)之间的数字。我们将这个数字乘以范围(max-min)。这将导致一个介于0(含)和范围之间的数字。
例如,随机(2,5)。我们将随机数0≤x<1乘以范围(5-2=3),因此我们现在有一个数x,其中0≤x<3。
为了强制函数将最大值和最小值都视为包含值,我们在范围计算中添加1:Math.random()*(max-min+1)。现在,我们将随机数乘以(5-2+1=4),得到一个数字x,即0≤x<4。如果我们对这个计算进行下限,我们得到一个整数:0≤x≤3,每个结果的可能性相等(1/4)。
最后,我们需要将其转换为请求值之间的整数。由于我们已经有一个介于0和(max-min)之间的整数,我们可以简单地通过添加最小值将值映射到正确的范围。在我们的示例中,我们将0到3之间的整数加2,得到2到5之间的整数。
数学.随机()
返回介于min(包含)和max(包含)之间的整数随机数:
function randomInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
或介于min(包含)和max(不包含)之间的任意随机数:
function randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
有用的示例(整数):
// 0 -> 10
Math.floor(Math.random() * 11);
// 1 -> 10
Math.floor(Math.random() * 10) + 1;
// 5 -> 20
Math.floor(Math.random() * 16) + 5;
// -10 -> (-2)
Math.floor(Math.random() * 9) - 10;
**总是很高兴被提醒(Mozilla):
Math.random()不提供加密安全的随机数字。不要将它们用于与安全相关的任何事情。使用Web加密API,更准确地说window.crypto.getRandomValues()方法。
使用此函数获取给定范围内的随机数:
function rnd(min, max) {
return Math.floor(Math.random()*(max - min + 1) + min);
}
// Example
function ourRandomRange(ourMin, ourMax) {
return Math.floor(Math.random() * (ourMax - ourMin + 1)) + ourMin;
}
ourRandomRange(1, 9);
// Only change code below this line.
function randomRange(myMin, myMax) {
var a = Math.floor(Math.random() * (myMax - myMin + 1)) + myMin;
return a; // Change this line
}
// Change these values to test your function
var myRandom = randomRange(5, 15);
对于具有范围的随机整数,请尝试:
function random(minimum, maximum) {
var bool = true;
while (bool) {
var number = (Math.floor(Math.random() * maximum + 1) + minimum);
if (number > 20) {
bool = true;
} else {
bool = false;
}
}
return number;
}