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


当前回答

这是我对一个范围内的随机数的看法,就像我想得到一个基数到指数范围内的一个随机数。例如,基数=10,指数=2,理想情况下给出从0到100的随机数,依此类推。

如果它有助于使用它,这里是:

// Get random number within provided base + exponent
// By Goran Biljetina --> 2012

function isEmpty(value) {
    return (typeof value === "undefined" || value === null);
}

var numSeq = new Array();

function add(num, seq) {
    var toAdd = new Object();
    toAdd.num = num;
    toAdd.seq = seq;
    numSeq[numSeq.length] = toAdd;
}

function fillNumSeq (num, seq) {
    var n;
    for(i=0; i<=seq; i++) {
        n = Math.pow(num, i);
        add(n, i);
    }
}

function getRandNum(base, exp) {
    if (isEmpty(base)) {
        console.log("Specify value for base parameter");
    }
    if (isEmpty(exp)) {
        console.log("Specify value for exponent parameter");
    }

    fillNumSeq(base, exp);

    var emax;
    var eseq;
    var nseed;
    var nspan;
    emax = (numSeq.length);
    eseq = Math.floor(Math.random()*emax) + 1;
    nseed = numSeq[eseq].num;
    nspan = Math.floor((Math.random())*(Math.random()*nseed)) + 1;
    return Math.floor(Math.random()*nspan) + 1;
}

console.log(getRandNum(10, 20), numSeq);

//Testing:
//getRandNum(-10, 20);
//console.log(getRandNum(-10, 20), numSeq);
//console.log(numSeq);

其他回答

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

数学.随机()

返回介于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()方法。

您可以使用此代码段,

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;
}
function randomRange(min, max) {
  return ~~(Math.random() * (max - min + 1)) + min
}

如果您使用Undercore.js,也可以使用

_.random(min, max)

为了获得最佳性能,您只需使用:

var r = (Math.random() * (maximum - minimum + 1) ) << 0