-3

I have a button that displays a quote and author from an array. I need the button to display a new quote/author each time the button is clicked. No two same quotes/authors in a row!

window.onload = function()
{
    //assign var to quoteText id contents
    var quoteSpan = document.getElementById("quoteText");

    //assign var to authorText id contents
    var authorSpan = document.getElementById("authorText");

    var oldQuoteIndex = -1;
    var submitButton = document.getElementById('submit');

    var quotes = [
        {'text': 'I like milk!', 'author': '-Biff'}, 
        {'text': 'Milk is nasty.', 'author': '-Jonn'}, 
        {'text': 'What do you mean?', 'author': '-Jay'}, 
        {'text': 'Milk. Mmm.', 'author': '-Don'}, 
        {'text': 'Milk is bad.', 'author': '-Denny'}
    ];  

    //function determining random quote
    function nextQuote() {

        do
        {
            //picks random quote from quotes arraw
            var newQuoteIndex = Math.floor(Math.random() * quotes.length);

        } while (newQuoteIndex == oldQuoteIndex); //while index of newly chosen quote is the same as the 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 is same as new index
    }

    //when button is clicked, quotation function starts
    submitButton.onclick = nextQuote;

}

2 Answers2

0

Replace your random index line with the following, as it is not getting the job done.

var randomnumber = Math.floor(Math.random() * (quotes.length + 1));

This will return a random index between [0 ... quotes.length]. Once you obtain the object at that index, remove it to prevent it from being selected again.

Source for random number.

Community
  • 1
  • 1
Brian Tracy
  • 6,801
  • 2
  • 33
  • 48
0

Why deal with what was picked?

Just remove it after you use it.

Basic example:

var orgArr = [0,1,2,3,4,5];
var rand = orgArr.slice(0)          //make a copy of the original
    .sort(function (){              //sort array 
         return Math.random() > .5; // very basic shuffle function
    });

while (rand.length) {               //just looping to show the items being removed
    var randomItem = rand.pop();    //get next random item and remove it
     console.log(randomItem);       //display it
}

In your case when the click happens, you do the popping.

epascarello
  • 204,599
  • 20
  • 195
  • 236