如何比较Math.random()方法生成的当前值与先前的值

时间:2016-02-16 14:56:44

标签: javascript

我是编程新手,最近开始学习JavaScript。我制作了一个随机生成引号的小程序。目前,该程序通过使用Math.random()方法从数组中获取引号。但有些时候随机生成的数字与之前相同,并且引用不会改变。

我想要的是,一旦生成报价,它就不应再显示,直到用户看到7个不同的报价。我如何通过使用纯JavaScript来实现这一目标? ({{3}})

如果您了解多种解决方案,请尽可能分享。

这是我的代码:

var heading = document.querySelector("h1");
var paragraph = document.querySelector("p");
var button = document.querySelector("button");
var randomQuotes = [
    "I am 1st quote.",
    "I am 2nd quote.",
    "I am 3rd quote.",
    "I am 4th quote.",
    "I am 5th quote",
    "I am 6th quote.",
    "I am 7th quote.",
    "I am 8th quote.",
    "I am 9th quote.",
    "I am 10th quote."
];

var generateQuote = function() {

   paragraph.innerHTML = randomQuotes[Math.floor(Math.random() * 10)];

}

button.onclick = generateQuote;
{{1}}

3 个答案:

答案 0 :(得分:0)

我会保存7个先前引号的列表,并确保当前的引号不在该列表中。更新的代码:

var heading = document.querySelector("h1");
var paragraph = document.querySelector("p");
var button = document.querySelector("button");
var randomQuotes = [
    "I am 1st quote.",
    "I am 2nd quote.",
    "I am 3rd quote.",
    "I am 4th quote.",
    "I am 5th quote.",
    "I am 6th quote.",
    "I am 7th quote.",
    "I am 8th quote.",
    "I am 9th quote.",
    "I am 10th quote."
];
var previousQuotes = [];

var generateQuote = function() {
    var quoteNumber = Math.floor(Math.random() * 10);
    if (previousQuotes.length > 6) {
        previousQuotes.shift();
    }
    while (previousQuotes.indexOf(quoteNumber) != -1) {
  	    quoteNumber = Math.floor(Math.random() * 10);
    }
    previousQuotes.push(quoteNumber);
    paragraph.innerHTML = randomQuotes[quoteNumber];
}

button.onclick = generateQuote;
<body>
    <h1>Random Quotes Generator</h1>
    <p>Click <strong>Generate</strong> button to see quotes.</p>
    <button>Generate!</button>
    <script src="script.js"></script>
</body>

答案 1 :(得分:0)

您可以在数组中保存先前显示的引号,并检查下一个随机生成的数字是否存在:

var generateQuote = function() {
    var quoteToShow = Math.floor(Math.random() * 10);
    while(last7quotes.indexOf(quoteToShow) > 0){
        quoteToShow = Math.floor(Math.random() * 10);
    }
    last7quotes.push(quoteToShow);
    if(last7quotes.length > 7){
        last7quotes.splice(0,1);
    }
    paragraph.innerHTML = randomQuotes[quoteToShow];    
}

See fiddle

答案 2 :(得分:0)

最短的方法是从阵列中拼接所选项目并将其推送到最后。随机值应介于0和2之间。这样可以保存最后7个选项。

&#13;
&#13;
var paragraph = document.querySelector("p"),
    button = document.querySelector("button"),
    randomQuotes = ["I am 1st quote.", "I am 2nd quote.", "I am 3rd quote.", "I am 4th quote.", "I am 5th quote.", "I am 6th quote.", "I am 7th quote.", "I am 8th quote.", "I am 9th quote.", "I am 10th quote."],
    generateQuote = function () {
        var quote = randomQuotes.splice(Math.random() * 3 | 0, 1)[0];
        randomQuotes.push(quote);
        paragraph.innerHTML = quote;
    }
button.onclick = generateQuote;
&#13;
<button>Generate!</button>
<p></p>
&#13;
&#13;
&#13;