I am making a trivia game that uses an array of objects.
const questions = [
{
question: 'What year did the United State become independent?',
answers: [
{ text: '1776', correct: true },
{ text: '1676', correct: false },
{ text: '1576', correct: false },
{ text: '1876', correct: false }
]
},
I think the correct way is to get the index of the correct answer by using .find, getting the the index of the selected answer, then use an if statement to compare the two. If they match then the console will log "correct" or "incorrect" otherwise. I am having trouble getting the index of corretAnswer and also selectedAnswer.
When I use this code and console log it, both variables return undefined.
const answerButtons = document.querySelectorAll('.answers-btn');
function checkAnswer() {
let correctAnswer = randomQuestion.answers.find((answer, index) => {
return answer[index] === true;
})
answerButtons.forEach((answerButton, index) => {
answerButton.addEventListener('click', () => {
let selectedAnswer = answerButton[index];
return selectedAnswer;
})
})
}
<button id="answers-btn-1" onclick="checkAnswer()" class="answers-btn"></button>
<button id="answers-btn-2" onclick="checkAnswer()" class="answers-btn"></button>
<button id="answers-btn-3" onclick="checkAnswer()" class="answers-btn"></button>
<button id="answers-btn-4" onclick="checkAnswer()" class="answers-btn"></button>