我需要在div中显示随机单词而不重复单词。随机单词将在每个随机秒(3-5秒)附加一个div。如果数组中的所有值都显示在div中,则会发出警报。
示例:
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);
}());
});
答案 0 :(得分:0)
这是一个有效的解决方案:
$(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();
});