📌  相关文章
📜  如何防止随机方法给出两个以上相同的数字 js site:stackoverflow.com - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:02:45.198000             🧑  作者: Mango

代码示例2
function setRandomInterval(min, max) {
    var last;
    if (min >= max) {
        throw 'Selected interval [' + min + ', ' + max + ') does not work for random numbers.';
    }
    return function () {
        var random;
        do {
            random = Math.floor(Math.random() * (max - min)) + min;
        } while (random === last);
        last = random;
        return random;
    };
}

var i,
    getRandom = setRandomInterval(0, 4);

for (i = 0; i < 100; i++) {
    console.log(getRandom());
}

setRandomInterval(4, 4); // throw error