【问题标题】:jQuery random count with no number repeat until end of loop没有数字重复的jQuery随机计数直到循环结束
【发布时间】:2013-05-29 01:59:50
【问题描述】:

我一直在努力。一个 jQuery 计数器函数,从 06 连续随机计数,但在循环结束之前不重复数字,即直到数组中的第 7 位计数。目前以下代码适用于我,但数字重复。请帮忙!

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

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

【问题讨论】:

  • 先生成7个不重复的随机数到一个数组中,然后循环遍历它们。在循环结束时重新启动该过程。现在的主要问题是每次迭代都会生成随机数。
  • 感谢您花时间考虑我的问题。

标签: jquery arrays math random counter


【解决方案1】:

您需要创建一个 7 位数的数组,按 shuffling the deck 随机化该数组(不要使用排序,尽管 fearless leader says 是什么),输出它们,然后重新开始。如果不维护已经输出的数字列表,就无法避免重复。

JS Fiddle

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

【讨论】:

  • 您的初始代码似乎是我正在寻找的。我仍在努力解决它。如果不走运,我会尝试您的更新以及对该线程的其他回复。我会及时通知你们。感谢您的帮助。
  • 感谢老专业人士花时间给我写一个解决方案。它工作得很好。
【解决方案2】:

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

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

【讨论】:

  • 谢谢奥斯汀。当没有数字时,您的代码将停止计数。我想要一个连续的计数。
【解决方案3】:
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);
}

FIDDLE

【讨论】:

  • 你做得很好Adeneo。您的回复很有帮助,我的问题也解决了。上帝保佑你!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-26
  • 2018-04-06
  • 1970-01-01
  • 2011-03-04
  • 1970-01-01
相关资源
最近更新 更多