简体   繁体   中英

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/

您可以先对数组进行混洗,然后从混洗后的数组中一一或四乘四地提取值。请参见shuffle方法: link

I think this is what you want: How to randomize (shuffle) a JavaScript array?

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. Please see original answer and links in it for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM