Home > Mobile >  Why is it that I am getting 'Uncaught TypeError: Cannot read properties of undefined (reading &
Why is it that I am getting 'Uncaught TypeError: Cannot read properties of undefined (reading &

Time:02-20

 const rndInt = Math.floor(Math.random() * 50);
 const arr = [];
 const input = document.getElementById('answer').value;

function displaySeq() {
        var i = 0;
        while (arr.length < 21) {
          arr[i] = {
              sequence: [],
              answer,
              guess: []
          };
          i  ;

          for (j=0; j < 7; j  ) {
              arr[i].sequence[0] = rndInt;
              arr[i].sequence.push(rndInt   j)
          }
       }  
        console.log(arr);
    }

I know that this error means that the variable does not have a value but im not sure what to do to resolve.

CodePudding user response:

You cannot access arr[0] when it is empty. So, first, you will have to push to the array and then call arr[0].

Also, you are incrementing i and then pushing into the array. So, initially, you are accessing arr[1] before defining arr[0].

Try this instead:

function displaySeq() {
     var i = 0;
     while (arr.length < 21) {
         arr.push({
             sequence: [],
             answer,
             guess: []
         });
         for (j=0; j < 7; j  ) {
             arr[i].sequence[0] = rndInt;
             arr[i].sequence.push(rndInt   j)
         }
         i  ;
     }  
     console.log(arr);
}
  • Related