如何在JavaScript中的两个指定变量之间生成随机整数,例如x=4和y=8将输出4、5、6、7、8中的任意一个?
当前回答
其他答案没有考虑到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
其他回答
所有这些解决方案都使用了太多的火力。您只需要调用一个函数:Math.random();
Math.random() * max | 0;
这将返回一个介于0(包含)和max(非包含)之间的随机整数。
如果需要介于0和max之间的变量,可以使用:
Math.floor(Math.random() * max);
// Example
function ourRandomRange(ourMin, ourMax) {
return Math.floor(Math.random() * (ourMax - ourMin + 1)) + ourMin;
}
ourRandomRange(1, 9);
// Only change code below this line.
function randomRange(myMin, myMax) {
var a = Math.floor(Math.random() * (myMax - myMin + 1)) + myMin;
return a; // Change this line
}
// Change these values to test your function
var myRandom = randomRange(5, 15);
我在W3Schools上找到了这个简单的方法:
Math.floor((Math.random() * max) + min);
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
注意:如果你先传入一个非整数值或更大的数字,你会得到不希望的行为,但除非有人要求,否则我不会深入研究参数检查代码,因为它与原始问题的意图相去甚远。
推荐文章
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 将整数转换为字符串,以逗号表示千
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?
- jQuery有不聚焦的方法吗?
- 反应钩子-正确的方式清除超时和间隔
- TypeScript枚举对象数组
- 在React.js中正确的img路径
- 在React.js中更新组件onScroll的样式
- onClick ReactJS调用多个函数
- 如何在JavaScript中转义单引号(')?