mercredi 18 janvier 2017

How do I avoid getting two of the same arrays when using Math.random?

I am playing around with a web app and ran into an issue with generating two different items and avoid getting the same item two times.

// ITEM 1
var item1 = [
  "i/itemname1.png",
  "i/itemname2.png",
  "i/itemname3.png"
];

var size = item1.length
var x = Math.floor(size*Math.random())

function getItem1() {
    document.getElementById("item1").src = item1[x];
}
getItem1();

// ITEM 2
var item2 = [
  "i/itemname1.png",
  "i/itemname2.png",
  "i/itemname3.png"
];

var size = item2.length
var x = Math.floor(size*Math.random())

function getItem2() {
    document.getElementById("item2").src = item2[x];
}
getItem2();

With this code I got a chance to get two of the same items. I need a solution to avoid this. Any ideas?




Aucun commentaire:

Enregistrer un commentaire