如何在JavaScript中的两个指定变量之间生成随机整数,例如x=4和y=8将输出4、5、6、7、8中的任意一个?
当前回答
random(min,max)生成介于min(含)和max(不含)之间的随机数Math.floor将数字向下舍入到最接近的整数函数generateRandomInteger(最小,最大){return数学下限(随机(最小值,最大值))}
因此,要生成一个介于4和8之间的随机整数,请使用以下参数调用上述函数:
generateRandomInteger(4, 9)
其他回答
如果需要介于0和max之间的变量,可以使用:
Math.floor(Math.random() * max);
我的生成0和n之间的随机数的方法,其中n<=10(n除外):
Math.floor((Math.random() * 10) % n)
数学.随机()
返回介于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()方法。
接受答案的问题
值得注意的是,接受的答案不能正确处理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+Lodash:
const generateRandomNumbers = (max, amount) => {
const numbers = [...Array(max).keys()];
const randomNumbers = sampleSize(numbers, amount);
return randomNumbers.sort((a, b) => a - b);
};
此外,TypeScript版本:
const generateRandomNumbers = (max: number, amount: number) => {
const numbers = [...Array(max).keys()];
const randomNumbers: number[] = sampleSize(numbers, amount);
return randomNumbers.sort((a: number, b: number) => a - b);
};
推荐文章
- 将整数转换为字符串,以逗号表示千
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?
- jQuery有不聚焦的方法吗?
- 反应钩子-正确的方式清除超时和间隔
- TypeScript枚举对象数组
- 在React.js中正确的img路径
- 在React.js中更新组件onScroll的样式
- onClick ReactJS调用多个函数
- 如何在JavaScript中转义单引号(')?
- Ng-repeat结束事件
- 谷歌MAP API未捕获的类型错误:无法读取属性“offsetWidth”为空