有没有办法用JavaScript生成指定范围内的随机数?
例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。
有没有办法用JavaScript生成指定范围内的随机数?
例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。
当前回答
这应该是有效的:
const getRandomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min
其他回答
尽管有许多答案,但结果几乎相同。我想补充一下我的答案并解释一下它的作用。因为理解它的工作方式比复制粘贴单行代码更重要。生成随机数只是简单的数学。
代码:
function getR(lower, upper) {
var percent = (Math.random() * 100);
// this will return number between 0-99 because Math.random returns decimal number from 0-0.9929292 something like that
//now you have a percentage, use it find out the number between your INTERVAL :upper-lower
var num = ((percent * (upper - lower) / 100));
//num will now have a number that falls in your INTERVAL simple maths
num += lower;
//add lower to make it fall in your INTERVAL
//but num is still in decimal
//use Math.floor>downward to its nearest integer you won't get upper value ever
//use Math.ceil>upward to its nearest integer upper value is possible
//Math.round>to its nearest integer 2.4>2 2.5>3 both lower and upper value possible
console.log(Math.floor(num), Math.ceil(num), Math.round(num));
}
如果起始数字是1,如示例(1-6)所示,则可以使用Math.ceil()方法代替Math.floor()。
Math.ceil(Math.random() * 6)
而不是
Math.floor(Math.random() * 6) + 1
我们不要忘记其他有用的数学方法。
我发现了一种使用ES6默认参数实现这一点的新方法。它非常漂亮,因为它允许一个参数或两个参数。这里是:
function random(n, b = 0) {
return Math.random() * (b-n) + n;
}
简短回答:使用简单的数组即可实现。
您可以在数组元素内交替。
即使您的值不是连续的,此解决方案也有效。值甚至不必是数字。
let array = [1, 2, 3, 4, 5, 6];
const randomValue = array[Math.floor(Math.random() * array.length)];
实例
返回1到10之间的随机数:
Math.floor((Math.random() * 10) + 1);
结果可能是:3.
试试看:这里
--
或使用lodash/descore:
_.随机(最小值,最大值)
文件:-罗达什-不受欢迎的