Javascript: Random Element From Array, Do While -
i have button displays quote , author array. need button display new quote/author each time button clicked. no 2 same quotes/authors in row!
window.onload = function() { //assign var quotetext id contents var quotespan = document.getelementbyid("quotetext"); //assign var authortext id contents var authorspan = document.getelementbyid("authortext"); var oldquoteindex = -1; var submitbutton = document.getelementbyid('submit'); var quotes = [ {'text': 'i milk!', 'author': '-biff'}, {'text': 'milk nasty.', 'author': '-jonn'}, {'text': 'what mean?', 'author': '-jay'}, {'text': 'milk. mmm.', 'author': '-don'}, {'text': 'milk bad.', 'author': '-denny'} ]; //function determining random quote function nextquote() { { //picks random quote quotes arraw var newquoteindex = math.floor(math.random() * quotes.length); } while (newquoteindex == oldquoteindex); //while index of newly chosen quote same index of old quote quotespan.innerhtml = quotes[newquoteindex].text; //while html's quotetext has random quote authorspan.innerhtml = quotes[newquoteindex].author; //while html's authortext has random author var oldquoteindex = newquoteindex; //while old index same new index } //when button clicked, quotation function starts submitbutton.onclick = nextquote; }
why deal picked?
just remove after use it.
basic example:
var orgarr = [0,1,2,3,4,5]; var rand = orgarr.slice(0) //make copy of original .sort(function (){ //sort array return math.random() > .5; // basic shuffle function }); while (rand.length) { //just looping show items being removed var randomitem = rand.pop(); //get next random item , remove console.log(randomitem); //display }
in case when click happens, popping.
Comments
Post a Comment