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?
I agree with the comment that a for loop with i < 1
is confusing. I don't understand what you are doing, but it does appear that your condition should be i < questions.length - 1
, or you should move the i++
to the end of the function.
As it currently stands, the code tests for a condition, immediately increments i
to break the condition, then tries to use i
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.