javascript - 随机问题生成器仅提示对象数组中的 1 个问题,并退出提示。而是提示所有问题
问题描述
我创建了一个对象数组,它从其中一个对象中随机选择一个问题并放入提示框中。
但是,它只提示 1 个问题,并且它打破了提示框。它不会一个接一个地提示所有其他问题。
let theQuestions = [
{
question: "What is the capital of Georgia?",
answer: "atlanta"
},
{
question: "What is the name of the Atlanta Baseball Team?",
answer: "atlanta braves"
},
{
question: "How many rings have the Atlanta Falcons Won?",
answer: 0
},
{
question: "What is the name of the NBA team in Miami?",
answer: "miami heat"
}
];// theQuestions array
const randomQuestions = ()=>{
const random = Math.floor(Math.random() *theQuestions.length);
return theQuestions[random];
}// randomQuestions
let question = randomQuestions().question;
let answer = randomQuestions().answer;
const askQuestions = prompt(question);
解决方案
如果您想连续提出所有问题,则需要某种循环。这是一个带有 while 循环的示例。
你代码中的这段代码无论如何都不会工作,因为你大多数时候都不会得到正确的答案:
let question = randomQuestions().question;
let answer = randomQuestions().answer;
如果您不想以随机顺序提出问题,则需要一个指示符来指示已经提出了哪个问题。一个简单的想法是从数组中删除提出的问题。
let theQuestions = [
{ question: "What is the capital of Georgia?", answer: "atlanta" },
{ question: "What is the name of the Atlanta Baseball Team?", answer: "atlanta braves" },
{ question: "How many rings have the Atlanta Falcons Won?", answer: 0 },
{ question: "What is the name of the NBA team in Miami?", answer: "miami heat" }
];
const randomQuestions = () => {
const index = Math.floor(Math.random() * theQuestions.length);
const question = theQuestions.splice(index, 1);
return question[0];
}
while(theQuestions.length) {
const question = randomQuestions();
const askedQuestion = prompt(question.question);
if (askedQuestion === null) {
console.log("User clicked cancel");
} else {
console.log(askedQuestion.toLowerCase() === question.answer);
}
}
推荐阅读
- c++ - 链接反对boost协程
- javascript - 有什么方法可以简化来自 google.script.run.withSuccessHandler 中 code.gs 的各种函数调用?Google Apps 脚本
- clojurescript - How to resolve Uncaught TypeError: clojure is undefined
- jquery - 预选相关下拉列表值以便使用 jquery 进行编辑
- jquery - jQuery var 不会保存
- python - 数值输入和二进制分类
- git - 忽略.gitignore中的文件夹,我们放`/`和不放有什么不同?
- sass - bootstrap 5中等效的zf-each-breakpoint是什么?
- php - 我在不使用 group by 的情况下从 MYSQL/PHP 获取一组字段的总和以及这些字段的整个数据集时遇到问题
- mongodb - MongoDB聚合嵌套字段最大值