如何在JavaScript中的两个指定变量之间生成随机整数,例如x=4和y=8将输出4、5、6、7、8中的任意一个?


当前回答

random(min,max)生成介于min(含)和max(不含)之间的随机数Math.floor将数字向下舍入到最接近的整数函数generateRandomInteger(最小,最大){return数学下限(随机(最小值,最大值))}

因此,要生成一个介于4和8之间的随机整数,请使用以下参数调用上述函数:

generateRandomInteger(4, 9)

其他回答

我想用一个例子来解释:

函数在JavaScript中生成5到25范围内的随机整数

概述:(i) 首先将其转换为范围-从0开始。(ii)然后将其转换为所需的范围(然后将非常易于完成)。

所以基本上,如果你想生成从5到25的随机整数,那么:

第一步:将其转换为范围-从0开始

从“max”和“min”中减去“lower/minimum number”。即

(5-5) - (25-5)

因此,范围将为:

0-20 ...正确的

第二步

现在,如果您希望两个数字都包含在范围内,即“0和20”,则公式为:

数学方程式:Math.floor((Math.random()*21))

一般公式:Math.floor((Math.random()*(max min+1)))

现在,如果我们将减去的/最小的数字(即5)添加到范围中,那么我们可以自动获得0到20的范围=>5到25

第三步

现在将减去的差值加在等式(即5)中,并将“Math.floor”添加到整个等式中:

数学方程式:Math.floor((Math.random()*21)+5)

一般公式:Math.floor((Math.random()*(max-min+1))+min)

因此,最终函数将是:

function randomRange(min, max) {
   return Math.floor((Math.random() * (max - min + 1)) + min);
}

下面是一个JavaScript函数的示例,它可以在不使用Math.random()的情况下生成任意指定长度的随机数:

function genRandom(length)
{
  const t1 = new Date().getMilliseconds();
  var min = "1", max = "9";
  var result;
  var numLength = length;
  if (numLength != 0)
  {
     for (var i = 1; i < numLength; i++)
     {
        min = min.toString() + "0";
        max = max.toString() + "9";
     }
  }
  else
  {
     min = 0;
     max = 0;
     return;
  }

  for (var i = min; i <= max; i++)
  {
       // Empty Loop
  }

  const t2 = new Date().getMilliseconds();
  console.log(t2);
  result = ((max - min)*t1)/t2;
  console.log(result);
  return result;
}

这里有一个函数,它生成一个介于最小值和最大值之间的随机数,两者都包含在内。

const randomInt = (max, min) => Math.round(Math.random() * (max - min)) + min;

Use:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
    </head>

    <body>
        <script>
            /*
                Assuming that window.crypto.getRandomValues
                is available, the real range would be from
                0 to 1,998 instead of 0 to 2,000.

                See the JavaScript documentation
                for an explanation:

                  https://developer.mozilla.org/en-US/docs/Web/API/RandomSource/getRandomValues
            */
            var array = new Uint8Array(2);
            window.crypto.getRandomValues(array);
            console.log(array[0] + array[1]);
        </script>
    </body>
</html>

Uint8Array创建一个最多三位数的数组,最大值为999。这段代码很短。

返回1到10之间的随机数:

Math.floor((Math.random()*10) + 1); 

返回1到100之间的随机数:

Math.floor((Math.random()*100) + 1)