I am incrementing an i count by defining the length of the array of objects, but the current condition is not working as expected (if (i < questions.length){})
let questions = [
{
question: 'This is question one?',
answerOne: 'Answer One 1',
answerTwo: 'Answer Two 1',
},
{
question: 'This is question Two?',
answerOne: 'Answer One 2',
answerTwo: 'Answer Two 2',
},
{
question: 'This is question Three?',
answerOne: 'Answer One 3 ',
answerTwo: 'Answer Two 3',
},
{
question: 'This is question Four?',
answerOne: 'Answer One 4 ',
answerTwo: 'Answer Two 4',
},
];
const yesBtn = document.querySelector ('#answer1');
const noBtn = document.querySelector ('#answer2');
const startBtn = document.querySelector ('#start');
const answersDiv = document.querySelector ('.answers');
const mainDiv = document.getElementById ('main');
let answer1Count = 0;
let answer2Count = 0;
const genHtml = () => {
let innerDiv = '';
for (let i = 0; i < 1; i++) {
console.log (questions[i].question, i);
innerDiv += `${questions[0].question}`;
if (answersDiv) {
answersDiv.style.display = 'block';
yesBtn.innerHTML = `${questions[0].answerOne}`;
noBtn.innerHTML = `${questions[0].answerTwo}`;
}
if (yesBtn) {
yesBtn.addEventListener ('click', () => {
if (i < questions.length) {
i++;
console.log (questions[i].question, i);
answer1Count++;
console.log ('answer 1 count =' + answer1Count);
const mainDiv = (document.getElementById (
'main'
).innerHTML = `${questions[i].question}
`);
yesBtn.innerHTML = `${questions[i].answerOne}`;
}
});
}
}
return innerDiv;
};
Error: Uncaught TypeError: Cannot read property 'question' of undefined
I know it's getting the error because i is still trying to increment, so the condition is not working?
let i=0inside the function. It can still be incremented inside the event handler