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


当前回答

当两个输入都是整数时,此实现可以正常工作。

function randomRange(myMin, myMax) {
  return Math.floor(
    Math.random() * (Math.ceil(myMax) - Math.floor(myMin) + 1) + myMin
  );
}

其他回答

以下是排字的解决方案

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)}`)

  }

这是我在网页上找到的东西:

function randomInt(e,t){return Math.floor(Math.random()*(t-e+1)+e)}

这是我对一个范围内的随机数的看法,就像我想得到一个基数到指数范围内的一个随机数。例如,基数=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);

返回1到10之间的随机数:

Math.floor((Math.random()*10) + 1); 

返回1到100之间的随机数:

Math.floor((Math.random()*100) + 1)

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

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