Javascript:随机数为5,在重复使用之前不重复

use*_*129 4 javascript random jquery numbers repeat

我使用下面的代码为我页面上的每个单独的图像分配一个随机类(五个).

$(this).addClass('color-' + (Math.floor(Math.random() * 5) + 1));
Run Code Online (Sandbox Code Playgroud)

它工作得很好,但我想做到这一点,以便连续不会有两个相同的类.

更好的是如果连续中没有两个相同,并且在使用所有5个之前它也不会多次使用任何类...就像在中,从数组中删除每个使用的类,直到所有这些类已经使用过,然后重新开始,不允许前5个中的最后一个和下一个5中的第一个是相同的颜色.

希望这是有道理的,并提前感谢任何帮助.

jfr*_*d00 19

您需要创建一个可能值的数组,每次从数组中检索随机索引以使用其中一个值时,都会将其从数组中删除.

这是一个通用的随机函数,在使用所有值之前不会重复.您可以调用它,然后只需将此索引添加到类名的末尾.

var uniqueRandoms = [];
var numRandoms = 5;
function makeUniqueRandom() {
    // refill the array if needed
    if (!uniqueRandoms.length) {
        for (var i = 0; i < numRandoms; i++) {
            uniqueRandoms.push(i);
        }
    }
    var index = Math.floor(Math.random() * uniqueRandoms.length);
    var val = uniqueRandoms[index];

    // now remove that value from the array
    uniqueRandoms.splice(index, 1);

    return val;

}
Run Code Online (Sandbox Code Playgroud)

工作演示:http://jsfiddle.net/jfriend00/H9bLH/


所以,你的代码就是这样:

$(this).addClass('color-' + (makeUniqueRandom() + 1));
Run Code Online (Sandbox Code Playgroud)

这是一个面向对象的表单,允许在应用程序的不同位置使用多个这样的表单:

// if only one argument is passed, it will assume that is the high
// limit and the low limit will be set to zero
// so you can use either r = new randomeGenerator(9);
// or r = new randomGenerator(0, 9);
function randomGenerator(low, high) {
    if (arguments.length < 2) {
        high = low;
        low = 0;
    }
    this.low = low;
    this.high = high;
    this.reset();
}

randomGenerator.prototype = {
    reset: function() {
        this.remaining = [];
        for (var i = this.low; i <= this.high; i++) {
            this.remaining.push(i);
        }
    },
    get: function() {
        if (!this.remaining.length) {
            this.reset();
        }
        var index = Math.floor(Math.random() * this.remaining.length);
        var val = this.remaining[index];
        this.remaining.splice(index, 1);
        return val;        
    }
}
Run Code Online (Sandbox Code Playgroud)

样品用法:

var r = new randomGenerator(1, 9);
var rand1 = r.get();
var rand2 = r.get();
Run Code Online (Sandbox Code Playgroud)

工作演示:http://jsfiddle.net/jfriend00/q36Lk4hk/