javascript - 如何使 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];
}
解决方案
我认为像 @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>
推荐阅读
- r - 求解 R 中的三对角幂矩阵
- r - 可以在 R 可格式化上下文中创建格式化程序以便有条件地应用它吗?
- elasticsearch - Kibana 中有缺陷的令牌配置为使用 SPNEGO
- python - Odoo合并2个整数字段
- angular - Angular - 仅当 URL 参数存在时如何执行查询
- javascript - 如何更改 Javascript 上的点击选项以在移动设备上工作?
- powershell - 如果之后抛出错误,则数组的 Powershell 写入输出会丢失
- amazon-web-services - 通过 AWS CloudFront 从单个 S3 存储桶为 SPA 多租户提供服务
- css - 为什么 Bootstrap 4.5 断点在我的 CSS 中不起作用?
- java - 想知道如何通过单击按钮为我重定向任何特定页面的期限确定期限吗?