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


当前回答

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

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

其他回答

最低和最高之间的随机整数:

function randomRange(low, high) {
  var range = (high-low);
  var random = Math.floor(Math.random()*range);
  if (random === 0) {
    random += 1;
  }
  return low + random;
}

这不是最优雅的解决方案,而是快速的解决方案。

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。这段代码很短。

我想,这是所有贡献中最简单的。

maxNum = 8,
minNum = 4

console.log(Math.floor(Math.random() * (maxNum - minNum) + minNum))

console.log(Math.floor(Math.random() * (8 - 4) + 4))

这将在控制台中记录4到8之间的随机数,包括4到8。

// Example
function ourRandomRange(ourMin, ourMax) {
    return Math.floor(Math.random() * (ourMax - ourMin + 1)) + ourMin;
}

ourRandomRange(1, 9);

// Only change code below this line.
function randomRange(myMin, myMax) {
    var a = Math.floor(Math.random() * (myMax - myMin + 1)) + myMin;
    return a; // Change this line
}

// Change these values to test your function
var myRandom = randomRange(5, 15);

这是我用来生成随机数的方法。

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

Math.random()返回一个介于0(含)和1(不含)之间的数字。我们将这个数字乘以范围(max-min)。这将导致一个介于0(含)和范围之间的数字。

例如,随机(2,5)。我们将随机数0≤x<1乘以范围(5-2=3),因此我们现在有一个数x,其中0≤x<3。

为了强制函数将最大值和最小值都视为包含值,我们在范围计算中添加1:Math.random()*(max-min+1)。现在,我们将随机数乘以(5-2+1=4),得到一个数字x,即0≤x<4。如果我们对这个计算进行下限,我们得到一个整数:0≤x≤3,每个结果的可能性相等(1/4)。

最后,我们需要将其转换为请求值之间的整数。由于我们已经有一个介于0和(max-min)之间的整数,我们可以简单地通过添加最小值将值映射到正确的范围。在我们的示例中,我们将0到3之间的整数加2,得到2到5之间的整数。