[英]Pull elements randomly from an array 3 by 3
I have an array with list items : 我有一个包含列表项的数组:
var listArray = [];
$("ul li").each(function(){
listArray.push($(this));
});
var item = listArray[Math.floor(Math.random()*listArray.length)];
item.css({
"transform":"scale(1)"
});
and i shuffled the array as it mentioned in answers but still i am not able to pull the elements from it one by one in intervals 而且我按照答案中提到的那样对数组进行了混洗,但仍然无法间隔一一拉出数组中的元素
if you have a better idea how to do it please tell me. 如果您有更好的主意,请告诉我。
DEMO : https://jsfiddle.net/rnfrxL1b/3/ 演示 : https : //jsfiddle.net/rnfrxL1b/3/
您可以先对数组进行混洗,然后从混洗后的数组中一一或四乘四地提取值。请参见shuffle方法: link
I think this is what you want: How to randomize (shuffle) a JavaScript array? 我认为这就是您想要的: 如何随机化(随机播放)JavaScript数组?
Accepted/most upvoted 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;
}
Which is the Fisher-Yates (aka Knuth) Shuffle, according to the author of the answer. 根据答案的作者,这就是Fisher-Yates(aka Knuth)随机播放。 Please see original answer and links in it for more details. 请查看原始答案及其中的链接以获取更多详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.