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

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


当前回答

数学不是我的强项,但我一直在做一个项目,我需要在正负之间生成很多随机数。

function randomBetween(min, max) {
    if (min < 0) {
        return min + Math.random() * (Math.abs(min)+max);
    }else {
        return min + Math.random() * max;
    }
}

例如

randomBetween(-10,15)//or..
randomBetween(10,20)//or...
randomBetween(-200,-100)

当然,您也可以添加一些验证,以确保您不使用数字以外的任何内容。还要确保最小值始终小于或等于最大值。

其他回答

函数randomIntFromInterval(min,max){//包括min和maxreturn Math.floor(Math.random()*(max-min+1)+min)}常量rndInt=随机IntFromInterval(1,6)控制台日志(rndInt)

它的“额外”之处在于它允许不以1开头的随机间隔。例如,你可以得到一个从10到15的随机数。灵活性

数学.随机()

返回介于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()方法。

尽管有许多答案,但结果几乎相同。我想补充一下我的答案并解释一下它的作用。因为理解它的工作方式比复制粘贴单行代码更重要。生成随机数只是简单的数学。

代码:

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));
}

排名靠前的解决方案在数学上与它下面的注释不同->Math.floor(Math.random()*6)+1。

任务:生成1到6之间的随机数。

Math.random()返回0到1之间的浮点数(例如0.344717274374或0.99341293123),我们将使用它作为百分比,因此Math.floor(Math.random*()*6)+1返回6的某个百分比(max:5,min:0)并加1。作者很幸运,下限是1.,因为百分比下限将“最大限度”返回小于6乘以1的5,并且1将被下限1加上。

当下限大于1时,就会出现问题。例如,任务:生成2到6之间的随机数。

(遵循作者的逻辑)Math.floor(Math.random()*6)+2,很明显,如果我们在这里得到5->Math.random()*66,然后加上2,结果将是7,超出了6的期望边界。

另一个例子,任务:在10到12之间随机生成。

(遵循作者的逻辑)Math.floor(Math.random()*12)+10,(抱歉重复)很明显,我们得到了数字“12”的0%-99%,这将远远超出12的期望边界。

因此,正确的逻辑是取下限和上限之间的差值加1,然后将其下限(减去1,因为Math.random()返回0-0.99,因此无法获得完全上限,这就是为什么我们将1添加到上限以获得最大99%的(上限+1),然后将它下限以消除多余)。一旦我们得到了(差值+1)的地板百分比,我们就可以添加下边界,以获得2个数字之间所需的随机数。

逻辑公式为:Math.floor(Math.random()*((up_boundary-low_boundary)+1))+10。

备注:即使是最高分答案下的评论也是不正确的,因为人们忘记了在差异上加1,这意味着他们永远不会得到上限(是的,如果他们根本不想得到,这可能是一种情况,但要求包括上限)。

基本上像骰子一样返回1-6,

return Math.round(Math.random() * 5 + 1);