![](/img/trans.png)
[英](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.