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


当前回答

我在W3Schools上找到了这个简单的方法:

Math.floor((Math.random() * max) + min);

其他回答

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

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

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

以下是排字的解决方案

function getRandomInt(min:number, max:number):number {
    return min+Math.round(Math.random() * (max-min));
  }

  for(let i:number=0; i<100; i++){
  console.log(`${i+1} >> ${getRandomInt(1,6)}`)

  }
var randomnumber = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;

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

如果需要介于0和max之间的变量,可以使用:

Math.floor(Math.random() *  max);