Jquery不重复的随机单词

Jquery不重复的随机单词,jquery,Jquery,我需要在div中显示随机单词,而不重复该单词。随机字将每随机秒(3-5秒)追加一个div。若数组中的所有值都显示在div中,则会发出警报 例如: b a c d ALERT('DONE') 不是: 我的代码: $(document).ready(function($) { words = ['a','b','c','d']; function doSomething() {} (function loop() { var rand = Math.round(Math.random()

我需要在div中显示随机单词,而不重复该单词。随机字将每随机秒(3-5秒)追加一个div。若数组中的所有值都显示在div中,则会发出警报

例如:

b
a
c
d
ALERT('DONE')
不是:

我的代码:

$(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);
}());
});
$(文档).ready(函数($){
单词=['a'、'b'、'c'、'd'];
函数doSomething(){}
(函数循环(){
var rand=Math.round(Math.random()*(3000-500))+500;
setTimeout(函数(){
var thisWord=words[Math.floor(Math.random()*words.length)];
$(“#容器”).append(“+thisWord+”);
doSomething();
loop();
},兰特);
}());
});

这里有一个可行的解决方案:

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

});
$(文档).ready(函数(){
变量词=['a','b','c','d'];
var getRandom=函数(){
var idx=Math.floor(Math.random()*words.length);
//获取单词并将其从数组中删除
返回字.拼接(idx,1)[0];
};
var appendIfMore=函数(){
var word=getRandom();
if(!word)return;//全部完成
$('')
.文本(word)
.appendTo(“#container”);
var delay=Math.round(Math.random()*(3000-500))+500;
setTimeout(appendIfMore,delay);
};
//开始添加内容
appendIfMore();
});

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

});