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


当前回答

一个名为randUpTo的函数,它接受一个数字并返回一个介于0和该数字之间的随机整数:

var randUpTo = function(num) {
    return Math.floor(Math.random() * (num - 1) + 0);
};

一个名为randBetween的函数,它接受表示一个范围的两个数字,并返回这两个数字之间的随机整数:

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

一个名为randFromTill的函数,它接受表示范围的两个数字,并返回一个介于min(含)和max(不含)之间的随机数

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

一个名为randFromTo的函数,接受表示范围的两个数字,并返回一个介于min(含)和max(含)之间的随机整数:

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

其他回答

要获得一个介于1和6之间的随机数,首先执行以下操作:

0.5 + (Math.random() * ((6 - 1) + 1))

这会将一个随机数乘以6,然后再加上0.5。接下来,通过以下操作将该数舍入为正整数:

Math.round(0.5 + (Math.random() * ((6 - 1) + 1))

这将数字四舍五入到最接近的整数。

或者为了更容易理解,请执行以下操作:

var value = 0.5 + (Math.random() * ((6 - 1) + 1))
var roll = Math.round(value);
return roll;

通常,使用变量执行此操作的代码为:

var value = (Min - 0.5) + (Math.random() * ((Max - Min) + 1))
var roll = Math.round(value);
return roll;

从最小值中减去0.5的原因是,仅使用最小值可以获得比最大值多1的整数。通过从最小值中减去0.5,基本上防止了最大值被舍入。

使用此函数获取给定范围内的随机数:

function rnd(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);

其他答案没有考虑到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

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

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