[英](JS) How can I randomly pull 3 unique elements from an array, EXCEPT for the 0th index?
[英]Pull elements randomly from an array 3 by 3
我有一個包含列表項的數組:
var listArray = [];
$("ul li").each(function(){
listArray.push($(this));
});
var item = listArray[Math.floor(Math.random()*listArray.length)];
item.css({
"transform":"scale(1)"
});
而且我按照答案中提到的那樣對數組進行了混洗,但仍然無法間隔一一拉出數組中的元素
如果您有更好的主意,請告訴我。
演示 : https : //jsfiddle.net/rnfrxL1b/3/
您可以先對數組進行混洗,然后從混洗后的數組中一一或四乘四地提取值。請參見shuffle方法: link
我認為這就是您想要的: 如何隨機化(隨機播放)JavaScript數組?
接受/最受歡迎的答案 :
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;
}
根據答案的作者,這就是Fisher-Yates(aka Knuth)隨機播放。 請查看原始答案及其中的鏈接以獲取更多詳細信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.