mardi 24 mai 2016

Why doesn't my simple routine to avoid generating two random numbers in a row work?

I'm doing the random quote generator Free Code Camp challenge, but don't want to have the same quote twice in a row. I came to the exact same conclusion as the person here did: http://ift.tt/1syWZZH

However, he says his works but mine still does not. My pen can be found here: http://ift.tt/1sO4EEt

And the code is:

  $(document).ready(function() {

    $("#getQuote").on("click", function() {
      $.getJSON("http://ift.tt/1syXnY8", function(json) {

        var html = "";
        var lastQuote = "";
        var whichQuoteToChoose = "";

        while (whichQuoteToChoose === lastQuote) {
          whichQuoteToChoose = Math.floor(Math.random() * 12); // returns a number between 0 and 11
        }
        lastQuote = whichQuoteToChoose;

        // this converts raw data into html

        json = json.filter(function(val) {
          return (val.id == whichQuoteToChoose);
        });

        json.forEach(function(val) {

          html += "<div class = 'quote'>"

          html += "<h2>\"" + val.Quotation + "\"</h2><h2>" + val.Quotee + "</h2>"

          html += "</div>"

        });

        $(".quote").html(html);

      });
    });
  });

With the while loop and the assignment immediately after it being what should, in theory, solve the problem.

Thanks for any and all help. Sorry to ask n00b questions here but the FCC help box can be a waste of time sometimes.




Aucun commentaire:

Enregistrer un commentaire