0

I've been trying hard at this. A jQuery counter function that counts from 0 to 6 continuously in random but no repeat of a number until end of the loop i.e. until the count of the 7th digit in the array. Currently the following code works for me but the numbers repeat. Please help!

function beginTimer() {
    if ($('#timer').html().length == 0) {
        timer(0) ;  
    }
}

function timer(i) {
    setTimeout("timer(" + (i) + ")", 1000);
    $('#timer').html(Math.floor(Math.random() * 6));
}
4

3 回答 3

1

您需要创建一个 7 位数字的数组,通过洗牌来随机化数组(不要使用排序,尽管无畏的领导者说了什么),输出它们,然后重新开始。如果不维护已经输出的数字列表,就无法避免重复。

JS小提琴

var digits = [0, 1, 2, 3, 4, 5, 6];
digits.shuffle = function () {
    var i = this.length,
        j, temp;
    while (--i >= 0) {
        j = Math.floor(Math.random() * (i + 1));
        temp = this[i];
        this[i] = this[j];
        this[j] = temp;
    }
    this.lastOutput = -1;
};
digits.shuffle();

var output = function () {
    var i = ++digits.lastOutput;
    if (i >= digits.length) {
        digits.shuffle();
        i = 0;
    }

    $('#timer').html(digits[i]);
    this.lastOutput = i;
    setTimeout(output, 1000);
};

output();
于 2013-06-02T22:31:38.970 回答
0
var counted = [];

function count() {
    var numb, go = true;

    while (go) {
        numb = Math.floor(Math.random() * 6);
        if (counted.indexOf(numb) == -1) counted.push(numb), go = false;
    }

    $('#timer').html(numb);
    if (counted.length > 5) counted = [];
    setTimeout(count, 300);
}

小提琴

于 2013-06-02T22:53:24.067 回答
0

您可以创建一个“数字”数组并从中挑选,直到它不再存在。

var digits = [];

// populate our digits array with 0-6
for(var i = 0; i < 6; i++)
    digits.push(i);

function timer() {
    // are there still digits remaining?
    if(!digits.length)
        return;

    // select a random digit and remove it from the array
    var digit = digits.splice( Math.floor( Math.random() * digits.length ), 1 );

    $('#timer').html(digit);

    setTimeout(timer, 1000);
}

JSFiddle

于 2013-06-02T22:36:53.750 回答