[英]Increment index by click event listener only up to length of array
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){}
)我通过定义对象数组的长度来增加 i 计数,但当前条件未按预期工作(
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 < 1
的 for 循环令人困惑的评论。 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.我不明白你在做什么,但看起来你的条件应该是
i < questions.length - 1
,或者你应该将i++
移动到 function 的末尾。
As it currently stands, the code tests for a condition, immediately increments i
to break the condition, then tries to use i
.就目前而言,代码测试条件,立即增加
i
以打破条件,然后尝试使用i
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.