简体   繁体   中英

Choosing Images randomly from an array

I have images in a directory and I am trying to use jQuery to assign them randomly to list items. I have it working, but I do NOT want to repeat images if they have already been used. This is my jquery:

var images = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg', '7.jpg', '8.jpg', '9.jpg', '10.jpg'];

$("#collageWrap li").each(function() {
    $('<img src="images/mosaic/' + images[Math.floor(Math.random() * images.length)] + '">').appendTo($(this));
});

If I have 10 images, and 20 list items, the idea would be to use the 10 images on the first 10 list items, and then the rest would be left blank. How can I change this code to ensure each image is used only once?

A solution would be to remove from the source array while taking the images at random :

$("#collageWrap li").each(function() {
    var index = Math.floor(Math.random()*images.length);
    var img = images.splice(index, 1)[0];
    $('<img src="images/mosaic/' + img + '">').appendTo($(this));
    return images.length>0;
});

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