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


当前回答

您可以使用此代码段,

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;
}

其他回答

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

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

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

其他答案没有考虑到0和1这两个完全合理的参数。相反,您应该使用圆形而不是天花板或地板:

function randomNumber(minimum, maximum){
    return Math.round( Math.random() * (maximum - minimum) + minimum);
}

console.log(randomNumber(0,1));  # 0 1 1 0 1 0
console.log(randomNumber(5,6));  # 5 6 6 5 5 6
console.log(randomNumber(3,-1)); # 1 3 1 -1 -1 -1

我想用一个例子来解释:

函数在JavaScript中生成5到25范围内的随机整数

概述:(i) 首先将其转换为范围-从0开始。(ii)然后将其转换为所需的范围(然后将非常易于完成)。

所以基本上,如果你想生成从5到25的随机整数,那么:

第一步:将其转换为范围-从0开始

从“max”和“min”中减去“lower/minimum number”。即

(5-5) - (25-5)

因此,范围将为:

0-20 ...正确的

第二步

现在,如果您希望两个数字都包含在范围内,即“0和20”,则公式为:

数学方程式:Math.floor((Math.random()*21))

一般公式:Math.floor((Math.random()*(max min+1)))

现在,如果我们将减去的/最小的数字(即5)添加到范围中,那么我们可以自动获得0到20的范围=>5到25

第三步

现在将减去的差值加在等式(即5)中,并将“Math.floor”添加到整个等式中:

数学方程式:Math.floor((Math.random()*21)+5)

一般公式:Math.floor((Math.random()*(max-min+1))+min)

因此,最终函数将是:

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

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