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


当前回答

我的生成0和n之间的随机数的方法,其中n<=10(n除外):

Math.floor((Math.random() * 10) % n)

其他回答

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

使用现代JavaScript+Lodash:

const generateRandomNumbers = (max, amount) => {
  const numbers = [...Array(max).keys()];
  const randomNumbers = sampleSize(numbers, amount);

  return randomNumbers.sort((a, b) => a - b);
};

此外,TypeScript版本:

const generateRandomNumbers = (max: number, amount: number) => {
  const numbers = [...Array(max).keys()];
  const randomNumbers: number[] = sampleSize(numbers, amount);

  return randomNumbers.sort((a: number, b: number) => a - b);
};

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

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

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

对于具有范围的随机整数,请尝试:

function random(minimum, maximum) {
  var bool = true;

  while (bool) {
    var number = (Math.floor(Math.random() * maximum + 1) + minimum);
    if (number > 20) {
      bool = true;
    } else {
      bool = false;
    }
  }

  return number;
}