如何在JavaScript中的两个指定变量之间生成随机整数,例如x=4和y=8将输出4、5、6、7、8中的任意一个?
当前回答
数学.随机()
返回介于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()方法。
其他回答
var randomnumber = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
数学.随机()
返回介于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()方法。
我想用一个例子来解释:
函数在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);
}
使用此函数获取给定范围内的随机数:
function rnd(min, max) {
return Math.floor(Math.random()*(max - min + 1) + min);
}
其他答案没有考虑到0和1这两个完全合理的参数。相反,您应该使用圆形而不是天花板或地板:
function randomNumber(minimum, maximum){
return Math.round( Math.random() * (maximum - minimum) + minimum);
}
console.log(randomNumber(0,1)); # 0 1 1 0 1 0
console.log(randomNumber(5,6)); # 5 6 6 5 5 6
console.log(randomNumber(3,-1)); # 1 3 1 -1 -1 -1