我有一个包含列表项的数组:
var listArray = [];
$("ul li").each(function(){
listArray.push($(this));
});
var item = listArray[Math.floor(Math.random()*listArray.length)];
item.css({
"transform":"scale(1)"
});就像答案中提到的那样,我对数组进行了洗牌,但是我还是不能隔一段时间从其中提取元素。
如果你有更好的方法,请告诉我。
发布于 2015-10-05 18:27:37
我想这就是你想要的:How to randomize (shuffle) a JavaScript array?
接受/投票最多的answer
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex ;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}根据答案的作者,那就是费舍-耶茨(又名Knuth)的洗牌。请参阅原文答案和链接,其中有更多的细节。
https://stackoverflow.com/questions/32955199
复制相似问题