jQuery随机单词,无需重复 [英] Jquery random words without repeating

查看:133
本文介绍了jQuery随机单词,无需重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在div中显示随机单词而不重复该单词.随机词将每隔随机秒(3-5秒)附加一个div.如果数组中的所有值都显示在div中,则警报将显示.

I need to display random words in div without repeating the word. The random words will append a div every random seconds (3-5 seconds). If all value in array displayed in div, alert will do.

示例:

b
a
c
d
ALERT('DONE')

不是:

b
a
b
c
d
d
a
a
c

我的代码:

$(document).ready(function($) { 
words = ['a','b','c','d'];
function doSomething() {}
(function loop() {
    var rand = Math.round(Math.random() * (3000 - 500)) + 500;
    setTimeout(function() {
            var thisWord = words[Math.floor(Math.random() * words.length)];
            $("#container").append("<div class=\"conversation\">"+thisWord+"<div class=\"conversation\">");
            doSomething();
            loop();  
    }, rand);
}());
});

推荐答案

这是一个可行的解决方案:

Here's a working solution:

$(document).ready(function() {
  var words = ['a', 'b', 'c', 'd'];

  var getRandom = function() {
    var idx = Math.floor(Math.random() * words.length);
    // grabs word and removes it from the array
    return words.splice(idx, 1)[0];
  };

  var appendIfMore = function() {
    var word = getRandom();
    if (!word) return; // all done

    $('<div class="conversation"/>')
      .text(word)
      .appendTo('#container');

    var delay = Math.round(Math.random() * (3000 - 500)) + 500;
    setTimeout(appendIfMore, delay);
  };

  // start appending stuff
  appendIfMore();

});

JSBIN

这篇关于jQuery随机单词,无需重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆