Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialCheryl Chao
5,555 PointsWhy I get result of "Uncaught TypeError: Cannot read property '0' of undefined"
let QandA = [["What's is my name?", "AMY"], ["Who is my boyfriend?", "KEVIN"], ["What is my favorite sport?", "BASKETBALL"], ["Where do I live?", "TAIPEI"], ["Who is my favorite cat?", "BON"]];
let correctAnswer = 0;
for (let i=0; i<=QandA.length; i++) {
if (prompt(QandA[i][0]).toUpperCase() === QandA[i][1]) {
correctAnswer += 1;
}
}
let messeage = You got ${correctAnswer} correct out of 5 questions.
;
document.querySelector('main').innerHTML = messeage ;
1 Answer
Jesse Ward
14,882 PointsCheck your for loop. you're testing while 'i' is less than or equal to the length of the array and then increasing the value of 'i'. When the loop gets to the length of the array, it continues to increase the length of 'i' one more, to actually be longer than the array. Your for loop should read:
for (let i=0; i<QandA.length; i++) {}
Jesse Ward
14,882 PointsJesse Ward
14,882 PointsSorry, meant to answer, not comment