首页 > 解决方案 > 如何使 JavaScript Bingo 生成器不重复相同的结果?

问题描述

我正在尝试制作感恩节宾果游戏生成器,并希望使这些短语只出现一次。

不知道该往哪个方向走。这是到目前为止的代码:

var questions = [
    "Can name all 3 Pilgrim ships",
    "Plays football",
    "Has an unusual Thanksgiving tradition",
    "Has a turkey disaster story",
    "Vegetarian",
    "Loves cranberry sauce",
    "Has celebrated Thanksgiving in another country",
    "Can name 5 things grateful for",
    "Makes a mean green bean casserole",
    "Eats mac and cheese on Thanksgiving",
    "Has worked retail on Black Friday",
    "Thanksgiving is favorite holiday",
    "Has seen a turkey in real life",
    "Watched the Macy's T-day parade in person",
    "Willing to share pie recipe",
    "Has attended a Friendsgiving",
    "Loves leftovers",
    "Dines out for Thanksgiving",
    "Can name 5 native American tribes",
    "Watches football",
    "Can gobble like a turkey",
    "Celebrates Canadian Thanksgiving",
    "Hates cranberry sauce",
    "Goes Black Friday shopping"
]

function newQuestion() {
 
    var randomNumber = Math.floor(Math.random() * (questions.length));
        document.getElementById('question-display').innerHTML = questions[randomNumber];
       
    }

标签: javascriptarraysrandomgenerator

解决方案


我认为像 @epascarello 注释掉的 Shuffle 和 pop 在这种情况下是完美的方式,这里有一个例子:

var questions = [
    "Can name all 3 Pilgrim ships",
    "Plays football",
    "Has an unusual Thanksgiving tradition",
    "Has a turkey disaster story",
    "Vegetarian",
    "Loves cranberry sauce",
    "Has celebrated Thanksgiving in another country",
    "Can name 5 things grateful for",
    "Makes a mean green bean casserole",
    "Eats mac and cheese on Thanksgiving",
    "Has worked retail on Black Friday",
    "Thanksgiving is favorite holiday",
    "Has seen a turkey in real life",
    "Watched the Macy's T-day parade in person",
    "Willing to share pie recipe",
    "Has attended a Friendsgiving",
    "Loves leftovers",
    "Dines out for Thanksgiving",
    "Can name 5 native American tribes",
    "Watches football",
    "Can gobble like a turkey",
    "Celebrates Canadian Thanksgiving",
    "Hates cranberry sauce",
    "Goes Black Friday shopping"
].sort(_=> Math.random() - 0.5);

document.querySelector("#get-question").onclick = function() {
  document.getElementById('question-display').innerHTML = questions.pop() || "There are no more questions!";    
}
<p  id="question-display"></p>
<button id="get-question">Get new question</button>


推荐阅读