如何在JavaScript中的两个指定变量之间生成随机整数,例如x=4和y=8将输出4、5、6、7、8中的任意一个?
当前回答
最低和最高之间的随机整数:
function randomRange(low, high) {
var range = (high-low);
var random = Math.floor(Math.random()*range);
if (random === 0) {
random += 1;
}
return low + random;
}
这不是最优雅的解决方案,而是快速的解决方案。
其他回答
伊奥努·G·斯坦写了一个很棒的答案,但对我来说有点太复杂了。因此,我在Math.floor(Math.random()*(max-min+1))+min)中找到了对相同概念的更简单的解释。
注意:在阅读Jason的解释之前,你应该知道的唯一重要的事情是“truncate”的定义。他在描述Math.floor()时使用了这个术语。牛津词典将“truncate”定义为:
通过切掉顶端或末端来缩短(某物)。
数学.随机()
返回介于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()方法。
返回1到10之间的随机数:
Math.floor((Math.random()*10) + 1);
返回1到100之间的随机数:
Math.floor((Math.random()*100) + 1)
Use:
function getRandomizer(bottom, top) {
return function() {
return Math.floor( Math.random() * ( 1 + top - bottom ) ) + bottom;
}
}
用法:
var rollDie = getRandomizer( 1, 6 );
var results = ""
for ( var i = 0; i<1000; i++ ) {
results += rollDie() + " "; // Make a string filled with 1000 random numbers in the range 1-6.
}
细分:
我们正在返回一个函数(从函数式编程中借用),当调用该函数时,将返回值bottom和top之间的随机整数,包括bottom。我们说“包含”是因为我们希望将底部和顶部都包含在可返回的数字范围内。这样,getRandomizer(1,6)将返回1、2、3、4、5或6。
(“底部”是较低的数字,“顶部”是较大的数字)
Math.random() * ( 1 + top - bottom )
Math.random()返回一个介于0和1之间的随机双精度,如果我们将其乘以1加上顶部和底部之间的差值,我们将得到一个介于介于0和1+b-a之间的双精度。
Math.floor( Math.random() * ( 1 + top - bottom ) )
Math.floor将数字向下舍入到最接近的整数。所以我们现在有了0和上下之间的所有整数。1看起来很令人困惑,但它需要存在,因为我们总是向下舍入,因此没有它就永远无法到达顶部数字。我们生成的随机小数需要在0到(1+上下)的范围内,这样我们就可以向下舍入,得到0到上下的整数:
Math.floor( Math.random() * ( 1 + top - bottom ) ) + bottom
上一个示例中的代码为我们提供了一个范围为0和上下的整数,因此我们现在需要做的就是将底部添加到该结果中,以获得范围为底部和顶部(含)的整数D
注意:如果你先传入一个非整数值或更大的数字,你会得到不希望的行为,但除非有人要求,否则我不会深入研究参数检查代码,因为它与原始问题的意图相去甚远。
这是我在网页上找到的东西:
function randomInt(e,t){return Math.floor(Math.random()*(t-e+1)+e)}
推荐文章
- 如何在vue-cli项目中更改端口号
- Angular 2模板中的标签是什么意思?
- JavaScript .includes()方法的多个条件
- 窗口。亲近与自我。close不关闭Chrome中的窗口
- 同步和异步编程(在node.js中)的区别是什么?
- 在d3.js中调整窗口大小时调整svg的大小
- 如何将两个字符串相加,就好像它们是数字一样?
- 绑定多个事件到一个监听器(没有JQuery)?
- 在JavaScript中将JSON字符串解析为特定对象原型
- 将字符串“true”/“false”转换为布尔值
- 如何使用JavaScript代码获得浏览器宽度?
- event.preventDefault()函数在IE中无法工作
- indexOf()和search()的区别是什么?
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误