JavaScript JavaScript Arrays Multidimensional Arrays Improve the Quiz – One Solution

Alexis Scriven
Alexis Scriven
2,244 Points

All of the arrays questions and answers show up in the alert. I'm not sure what is incorrect.

In the alert I see all of the questions and answers I created. I think my code is the exact same as Guil's so I am not sure why it doesn't show them individually.

// 1. Create a multidimensional array to hold quiz questions and answers const questions = [ ['How many planets are in the Solar System?', '8'], ['How many continents are there?', '7'], ['How many legs does an insect have?', '6'], ['What year was JavaScript created?', '1995']
];

// 2. Store the number of questions answered correctly const correct = []; const incorrect = []; let correctAnswers = 0

/*

  1. Use a loop to cycle through each question
    • Present each question to the user
    • Compare the user's response to answer in the array
    • If the response matches the answer, the number of correctly answered questions increments by 1 */ for ( let i = 0; i < questions.length; i++) { let question = questions[i][0]; let answer = questions[i][1]; let response = prompt(questions);

if ( response === answer ) { correctAnswers++; correct.push(question); } else { incorrect.push(question); } }

function createListItems(arr) { let items = ''; for (let i = 0; i < arr.length; i++) { items += <li>${arr[i]}</li>; } return items; }

// 4. Display the number of correct answers to the user let html = ` <h1>You got ${correctAnswers} question(s) correct</h1> <h2>You got these questions right:</h2> <ol>${ createListItems(correct) }</ol>

<h2>You got these questions wrong:</h2> <ol>${ createListItems(incorrect) }</ol> `;

document.querySelector('main').innerHTML = html

1 Answer

Hi, Alexis Scriven

That's because you were using questions in the prompt instead of question.

questions contain the whole array of questions. And question is the variable going in the loop when every time the prompt is called.

You just have to change your variable to question in the prompt.

Like this:

  let question = questions[i][0]; 
  let answer = questions[i][1]; 
  let response = prompt(question);

Also, it's a good practice to wrap your code around 3 backticks (```) on the line before and after. It will look the way mine did, otherwise it's very hard to read.