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


当前回答

下面是一个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;
}

其他回答

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

数学.随机()

返回介于min(包含)和max(包含)之间的整数随机数:

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

或介于min(包含)和max(不包含)之间的任意随机数:

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

有用的示例(整数):

// 0 -> 10
Math.floor(Math.random() * 11);

// 1 -> 10
Math.floor(Math.random() * 10) + 1;

// 5 -> 20
Math.floor(Math.random() * 16) + 5;

// -10 -> (-2)
Math.floor(Math.random() * 9) - 10;

**总是很高兴被提醒(Mozilla):

Math.random()不提供加密安全的随机数字。不要将它们用于与安全相关的任何事情。使用Web加密API,更准确地说window.crypto.getRandomValues()方法。

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

伊奥努·G·斯坦写了一个很棒的答案,但对我来说有点太复杂了。因此,我在Math.floor(Math.random()*(max-min+1))+min)中找到了对相同概念的更简单的解释。

注意:在阅读Jason的解释之前,你应该知道的唯一重要的事情是“truncate”的定义。他在描述Math.floor()时使用了这个术语。牛津词典将“truncate”定义为:

通过切掉顶端或末端来缩短(某物)。

您可以使用此代码段,

let randomNumber = function(first, second) {
    let number = Math.floor(Math.random()*Math.floor(second));
    while(number < first) {

        number = Math.floor(Math.random()*Math.floor(second));
    }
    return number;
}