Home > OS >  Writing a simple quiz, how to access the choices that are defined in a variable
Writing a simple quiz, how to access the choices that are defined in a variable

Time:06-08

Probably something very basic but I'm trying to write a simple JS quiz, and I have an array for the questions, choices and answers all in one:

const questions = [
  {
    question: "What is JavaScript?",
    choices: ["An interesting coffee blend", "Something your doctor uses", "A new movie", "A coding language"],
    answer: 3
  },
  {
    question: "Which of the following keywords is used to define a variable?",
    choices: ["var", "let", "Both A and B", "None of the above"],
    answer: 2
  },

etc..

I can choose a specific question from the array, but not the relevant choices or answers from that.

function grabQuestion() {
  for (let i = 0; i < questions.length; i  ) {
    const question = questions[i].question
    const choices = questions[i].choices
    questionEl.textContent = question
    console.log(choices)
    console.log(answer)
  }
}

This just lists the all of the questions.choices not the index that I've generated in the for loop.

I know it's simple but I'm just not seeing it.

CodePudding user response:

You just forgot to define answer I think. Just add this.

const answer = questions[i].answer

CodePudding user response:

As per my understanding, You want to fetch a choices and answer of the specific question instead to get all the answer and choices ? If Yes, Then you can get that dynamically from the array based on the question text or by assigning an id to each question object.

Let me explain that with an example/demo :

const questions = [
{
  question: "What is JavaScript?",
  choices: ["An interesting coffee blend", "Something your doctor uses", "A new movie", "A coding language"],
  answer: 3
},
{
  question: "Which of the following keywords is used to define a variable?",
  choices: ["var", "let", "Both A and B", "None of the above"],
  answer: 2
}];

function getQuestionDetails(questionText) {
  return questions.find(({ question }) => questionText === question);
}

const selectedQuestionDetails = getQuestionDetails('What is JavaScript?');

console.log('choices', selectedQuestionDetails.choices);

console.log('answer', selectedQuestionDetails.answer);

  • Related