如何在JavaScript中的两个指定变量之间生成随机整数,例如x=4和y=8将输出4、5、6、7、8中的任意一个?
当前回答
为了获得最佳性能,您只需使用:
var r = (Math.random() * (maximum - minimum + 1) ) << 0
其他回答
最低和最高之间的随机整数:
function randomRange(low, high) {
var range = (high-low);
var random = Math.floor(Math.random()*range);
if (random === 0) {
random += 1;
}
return low + random;
}
这不是最优雅的解决方案,而是快速的解决方案。
接受答案的问题
值得注意的是,接受的答案不能正确处理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>
使用此函数获取给定范围内的随机数:
function rnd(min, max) {
return Math.floor(Math.random()*(max - min + 1) + min);
}
function randomRange(min, max) {
return ~~(Math.random() * (max - min + 1)) + min
}
如果您使用Undercore.js,也可以使用
_.random(min, max)
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。这段代码很短。
推荐文章
- 将整数转换为字符串,以逗号表示千
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?
- jQuery有不聚焦的方法吗?
- 反应钩子-正确的方式清除超时和间隔
- TypeScript枚举对象数组
- 在React.js中正确的img路径
- 在React.js中更新组件onScroll的样式
- onClick ReactJS调用多个函数
- 如何在JavaScript中转义单引号(')?
- Ng-repeat结束事件
- 谷歌MAP API未捕获的类型错误:无法读取属性“offsetWidth”为空