JavaScript JavaScript Arrays Multidimensional Arrays Build a Quiz Challenge – One Solution

Why 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 ;

Jesse Ward
Jesse Ward
13,861 Points

Sorry, meant to answer, not comment

1 Answer

Jesse Ward
Jesse Ward
13,861 Points

Check 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++) {}