有没有办法用JavaScript生成指定范围内的随机数?

例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。


当前回答

简短回答:使用简单的数组即可实现。

您可以在数组元素内交替。

即使您的值不是连续的,此解决方案也有效。值甚至不必是数字。

let array = [1, 2, 3, 4, 5, 6];
const randomValue = array[Math.floor(Math.random() * array.length)];

其他回答

ES6/Arrow函数版本基于Francis的代码(即顶级答案):

const randomIntFromInterval = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);

重要的

The following code works only if the minimum value is `1`. It does not work for minimum values other than `1`.

如果你想得到一个介于1(且只有1)和6之间的随机整数,你可以计算:

const rndInt=数学地板(Math.random()*6)+1控制台日志(rndInt)

哪里:

1是起始编号6是可能结果的数量(1+start(6)-end(1))

使用可重用的随机函数。

function randomNum(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
randomNum(1, 6);
var x = 6; // can be any number
var rand = Math.floor(Math.random()*x) + 1;

或者,在Undercore

_.random(min, max)