vendredi 27 mars 2015

Best way to randomly pull from an array?

I have a website that will give you a random fact from Wikipedia when you click a big red button. I have heard from a few people that they are getting certain facts repeatedly, even though there are over 200.


The big red button has onclick="giveafact()" which triggers this function:



function giveafact(){ //instead of relisting all array items here, add all the other arrays to this one
var factsList= foodFactsList.concat(musicFactsList,historyFactsList,popFactsList,sportsFactsList,technologyFactsList,televisionFactsList,miscFactsList);
randomFact = Math.floor(Math.random()*factsList.length);
document.getElementById("total").innerHTML=factsList.length;
document.getElementById("fact").innerHTML=factsList[randomFact];
updateShareLinks();
return false;
}


Basically, I have 8 different arrays of facts as you can see in var factsList above. This is so the user can filter by fact. By default, there is no filter so all lists are concatenated.


If it helps, the full .js file is here: http://ift.tt/1D7gwEO. These random "give a fact" functions start at about line 442, with the arrays above them. (Pardon the messy code, I know I mix jQuery and Javascript a lot.)


The site is http://thewikifix.com, if it helps anyone to look at all the code.


I'm just trying to see if there's a way to better randomize the facts than I currently have, maybe by adding a function that won't allow a fact to show up twice in a row, or something similar.


Any suggestions would be great!





Aucun commentaire:

Enregistrer un commentaire