I've created an array of objects that I need my for loop to go through. However, when I run this code, I only ever seen the first question and its answers. What am I doing wrong? Thank you in advance!
// An array of objects containing questions, answers, and the correct answers.
const questionArray = [
{
Q: "TestingQ1",
A: [
"Testing2",
"Testing3",
"Testing4",
"Testing5"
],
Correct: "Testing2"
},
{
Q: "TestingQ2",
A: [
"Testing2-2",
"Testing3-2",
"Testing4-2",
"Testing5-2"
],
Correct: "Testing3-2"
}
];
// Set to zero to target the first index in an array of objects.
let questionIndex = 0;
// showQuestions is equal to elements with the "show-questions" class. Here, a section.
let showQuestions = document.querySelector(".show-questions");
// showAnswers is equal to the elements in the "show-answers" class. Here, a section.
let showAnswers = document.querySelector(".show-answers");
// results is equal to the "results" id. Here, a span.
let results = document.querySelector("#results");
// Create a function that displays questions
function displayQuestions() {
showQuestions.textContent = questionArray[questionIndex].Q;
console.log(showAnswers);
for (let i = 0; i < questionArray[questionIndex].A.length; i++) {
let answerButton = document.createElement("button");
answerButton.textContent = questionArray[questionIndex].A[i];
// Define the function here to check the answers
answerButton.onclick = function checkAnswers() {
// If the submission is equal to Correct...
if (answerButton.innerText === questionArray[questionIndex].Correct) {
// ...show this confirmation message.
results.textContent = "Right on, popcorn! That's correct.";
console.log(checkAnswers);
// If the submission is not equal to Correct...
} else {
// ...show this error message and...
results.textContent = "Sorry, no such luck. Try again!";
// ...deduct 10 seconds from the clock.
secondsLeft -= 10;
}
};
showAnswers.appendChild(answerButton);
}