首页 > 解决方案 > 随机问题生成器仅提示对象数组中的 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);

标签: javascriptarraysobjectecmascript-6

解决方案


如果您想连续提出所有问题,则需要某种循环。这是一个带有 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);
  }
}


推荐阅读