如何在JavaScript中的两个指定变量之间生成随机整数,例如x=4和y=8将输出4、5、6、7、8中的任意一个?
当前回答
返回1到10之间的随机数:
Math.floor((Math.random()*10) + 1);
返回1到100之间的随机数:
Math.floor((Math.random()*100) + 1)
其他回答
使用此函数获取给定范围内的随机数:
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);
Use:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<script>
/*
Assuming that window.crypto.getRandomValues
is available, the real range would be from
0 to 1,998 instead of 0 to 2,000.
See the JavaScript documentation
for an explanation:
https://developer.mozilla.org/en-US/docs/Web/API/RandomSource/getRandomValues
*/
var array = new Uint8Array(2);
window.crypto.getRandomValues(array);
console.log(array[0] + array[1]);
</script>
</body>
</html>
Uint8Array创建一个最多三位数的数组,最大值为999。这段代码很短。
接受答案的问题
值得注意的是,接受的答案不能正确处理min大于max的情况。下面是一个例子:
min=数学ceil(2);max=数学楼层(1);对于(变量i=0;i<25;i++){console.log(Math.floor(Math.random()*(max-min+1))+min);}
此外,如果你不熟悉这个小算法,阅读起来有点啰嗦和不清楚。
为什么Randojs是更好的解决方案?
Randomjs自动处理最小值大于最大值的情况(并且它是加密安全的):
对于(var i=0;i<25;i++)console.log(rando(2,1));<script src=“https://randojs.com/1.0.0.js“></script>
它还处理负数、零和其他所有你期望的东西。如果您需要执行浮点运算或使用其他变量类型,也有一些选项,但我不会在这里讨论它们。它们在网站上,因此如果需要,您可以深入研究。最后的原因很明显。从风格上看,它更干净,更容易阅读。
TL;医生,给我解决方案。。。
randojs.com使这一点和许多其他常见的随机性变得强大、可靠、简单/可读:
console.log(随机(20,30));<script src=“https://randojs.com/1.0.0.js“></script>
我想用一个例子来解释:
函数在JavaScript中生成5到25范围内的随机整数
概述:(i) 首先将其转换为范围-从0开始。(ii)然后将其转换为所需的范围(然后将非常易于完成)。
所以基本上,如果你想生成从5到25的随机整数,那么:
第一步:将其转换为范围-从0开始
从“max”和“min”中减去“lower/minimum number”。即
(5-5) - (25-5)
因此,范围将为:
0-20 ...正确的
第二步
现在,如果您希望两个数字都包含在范围内,即“0和20”,则公式为:
数学方程式:Math.floor((Math.random()*21))
一般公式:Math.floor((Math.random()*(max min+1)))
现在,如果我们将减去的/最小的数字(即5)添加到范围中,那么我们可以自动获得0到20的范围=>5到25
第三步
现在将减去的差值加在等式(即5)中,并将“Math.floor”添加到整个等式中:
数学方程式:Math.floor((Math.random()*21)+5)
一般公式:Math.floor((Math.random()*(max-min+1))+min)
因此,最终函数将是:
function randomRange(min, max) {
return Math.floor((Math.random() * (max - min + 1)) + min);
}