为什么我的简单例程不能避免连续生成两个随机数?



我正在做随机报价生成器自由代码营地挑战,但不想连续两次使用相同的报价。我得出的结论和这里的人一模一样:https://codereview.stackexchange.com/questions/62018/prevent-repetitive-random-numbers

然而,他说他的作品,但我的作品仍然没有。我的笔可以在这里找到:http://codepen.io/thomasdean/pen/qZGQxK

代码是:

  $(document).ready(function() {
    $("#getQuote").on("click", function() {
      $.getJSON("http://codepen.io/thomasdean/pen/Yqmgyx.js", 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);
      });
    });
  });

从理论上讲,while 循环和紧随其后的赋值应该解决问题。

感谢您的任何和所有帮助。

只是不要在每个点击事件上重写lastQuote和whichQuoteToChoose。 所以我将这些变量移出了点击事件:)

     $(document).ready(function() {
     var lastQuote = "";
    var whichQuoteToChoose = "";
     $("#getQuote").on("click", function() {
         $.getJSON("http://codepen.io/thomasdean/pen/Yqmgyx.js", function(json) {
        var html = "";

        //alert(lastQuote)
        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);
      });
    });
  });

相关内容

  • 没有找到相关文章

最新更新