Error: "Cannot read property '2' of undefined" Why?


#1
function lightColumn(column)
{
  var text;
  for(var i=1;i<=countRows();i++)
  {
    text += GRID[i][convertColumn(column)];
  }
  return text;
}

ConverColumn return an integer so…

function convertColumn(coordinates)
{
  let letters = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
  for(var i = 0; i < letters.length; i++)
  {
    if(coordinates[0] == letters[i]) return i;
  }
}

#2

Not sure about that specific error message, but your strategy is not right. You are trying to build a text String by adding characters to it, but the question requires an Array to be returned.
Your Way: " ^ ~ v “;
Array Way: [”", “^”, “v”, “”];
Start with an empty array and PUSH each item onto it with your for loop


#3
function lightColumn(column)
{
  var text = [];
  for(var i=1;i<=countRows();i++)
  {
    text[i] = GRID[i][convertColumn(column)-1];
  }
  return text;
}

Ok, then this ?! Same error occures!


#4

Remember that Javascript indexes start at 0, not 1. I think you’ve got it right almost everywhere.


#5
function lightColumn(column)
{
  var text = [];
  for(var i=0;i<=countRows();i++)
  {
    text[i] = GRID[i][convertColumn(column)-1];
  }
  return text;
}

Your code could not run: “Cannot read property ‘2’ of undefined”


#6

In the for loop i<=countRows(). I think this would go out of bounds for the array. Try i<countRows()

Also your convertColumn function already returns from a zero base array, so you shouldn’t need the -1.


#7

I believe you said you come from a C++ background, so I understand why you did:

text[i] = GRID[i][convertColumn(column)];

But if you plan on continuing with javascript, I found it advantageous to use the built in Array functions. Here
is a link to Array.push.

text.push(GRID[i][convertColumn(column)]);

Plus along the left side of the site there are many other built in functions you can learn about.