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

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


当前回答

或者,在Undercore

_.random(min, max)

其他回答

排名靠前的解决方案在数学上与它下面的注释不同->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,这意味着他们永远不会得到上限(是的,如果他们根本不想得到,这可能是一种情况,但要求包括上限)。

重要的

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

其他解决方案:

(数学随机()*6|0)+1~~(数学随机()*6)+1

联机尝试

这个简单的功能很方便,在任何情况下都可以使用(经过充分测试)。此外,结果的分布已经过充分测试,100%正确。

function randomInteger(pMin = 1, pMax = 1_000_000_000)
//Author: Axel Gauffre. 
//Here: https://stackoverflow.com/a/74636954/5171000
//Inspired by: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#getting_a_random_number_between_two_values
//
//This function RETURNS A RANDOM INTEGER between pMin (INCLUDED) and pMax (INCLUDED).
//  - pMin and pMax should be integers.
//  - HOWEVER, if pMin and/or pMax are FLOATS, they will be ROUNDED to the NEAREST integer.
//  - NEGATIVE values ARE supported.
//  - The ORDER of the 2 arguments has NO consequence: If pMin > pMax, then pMin and pMax will simply be SWAPPED.
//  - If pMin is omitted, it will DEFAULT TO 1.
//  - If pMax is omitted, it will DEFAULT TO 1 BILLION.
//
//This function works in ANY cases (fully tested).
//Also, the distribution of the results has been fully tested and is 100% correct.
{
    pMin = Math.round(pMin);
    pMax = Math.round(pMax);
    if (pMax < pMin) { let t = pMin; pMin = pMax; pMax = t;}
    return Math.floor(Math.random() * (pMax+1 - pMin) + pMin);
}

此函数可以生成介于(包括)最小值和最大值之间的随机整数:

function randomNumber(min, max) {
  if (min > max) {
    let temp = max;
    max = min;
    min = temp;
  }

  if (min <= 0) {
    return Math.floor(Math.random() * (max + Math.abs(min) + 1)) + min;
  } else {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
}

例子:

randomNumber(-2, 3); // can be -2, -1, 0, 1, 2 and 3
randomNumber(-5, -2); // can be -5, -4, -3 and -2
randomNumber(0, 4); // can be 0, 1, 2, 3 and 4
randomNumber(4, 0); // can be 0, 1, 2, 3 and 4