0

So on my page I am displaying 5 random images in a line, when I reload the page the images change, that works. but sometimes 2 of the same images that are picked are the same because I use the same Array for all 5 images, is there a way to prevent this from happening?

Thanks!

this is the code I have so far:

images = new Array();
    
    images[0] = "<a href ='001.html'><img src='/images/001.jpg' width='125' height='125'></a>";
    images[1] = "<a href ='002.html'><img src='/images/002.jpg' width='125' height='125'></a>";
    images[2] = "<a href ='003.html'><img src='/images/003.jpg' width='125' height='125'></a>";
    images[3] = "<a href ='004.html'><img src='/images/004.jpg' width='125' height='125'></a>";
    images[4] = "<a href ='005.html'><img src='/images/005.jpg' width='125' height='125'></a>";
    images[5] = "<a href ='006.html'><img src='/images/006.jpg' width='125' height='125'></a>";
    images[6] = "<a href ='007.html'><img src='/images/007.jpg' width='125' height='125'></a>";
    images[7] = "<a href ='008.html'><img src='/images/008.jpg' width='125' height='125'></a>";
    images[8] = "<a href ='009.html'><img src='/images/009.jpg' width='125' height='125'></a>";
    images[9] = "<a href ='010.html'><img src='/images/010.jpg' width='125' height='125'></a>";
    images[10] = "<a href ='011.html'><img src='/images/011.jpg' width='125' height='125'></a>";
    
    Number = Math.floor(Math.random()*images.length)
    document.write(images[Number]);
Kasper_L
  • 3
  • 1

1 Answers1

0

One way would be to ensure that you only initialize the array once, and then remove the element you randomly selected so that it can't be selected again, using images.splice(Number, 1). (But don't name your variable Number.)

var options = ['a', 'b', 'c', 'd', 'e'];

function selectItem() {
  var n, item;

  if (options.length === 0) { return; }

  var n = Math.floor(Math.random() * options.length);

  item = options[n];

  options.splice(n, 1);

  return item;
};

Here is a jsfiddle that demonstrates the basic technique.

You could also use a function that encapsulates this logic:

function randomItemDispenser(items) {
  return function () {
    var n;

    if (items.length !== 0) {
      n = Math.floor(Math.random() * items.length);

      return items.splice(n, 1)[0];
    }
  };
}

This function accepts an array as an argument and returns a function that, when called, will remove and return a random element from that array, until the array becomes empty:

var dispenser = randomItemDispenser(['a', 'b', 'c', 'd', 'e']);
var i;

while ((i = dispenser()) !== undefined) {
    // Do something with i
}
cdhowie
  • 158,093
  • 24
  • 286
  • 300