如何在JavaScript中的两个指定变量之间生成随机整数,例如x=4和y=8将输出4、5、6、7、8中的任意一个?
当前回答
function randomRange(min, max) {
return ~~(Math.random() * (max - min + 1)) + min
}
如果您使用Undercore.js,也可以使用
_.random(min, max)
其他回答
我想,这是所有贡献中最简单的。
maxNum = 8,
minNum = 4
console.log(Math.floor(Math.random() * (maxNum - minNum) + minNum))
console.log(Math.floor(Math.random() * (8 - 4) + 4))
这将在控制台中记录4到8之间的随机数,包括4到8。
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()方法。
这里有一个函数,它生成一个介于最小值和最大值之间的随机数,两者都包含在内。
const randomInt = (max, min) => Math.round(Math.random() * (max - min)) + min;
当两个输入都是整数时,此实现可以正常工作。
function randomRange(myMin, myMax) {
return Math.floor(
Math.random() * (Math.ceil(myMax) - Math.floor(myMin) + 1) + myMin
);
}