Why? Just Why? :(


#1

var newArray= new Array();

newArray[0][0] = 0;
newArray[0][1] = 1;
newArray[0][2] = 2;

newArray[1][0] = 0;
newArray[1][1] = 1;
newArray[1][2] = 2;

newArray[2][0] = 0;
newArray[2][1] = 1;
newArray[2][2] = 2;

The error I get: TypeError: Cannot set property '0' of undefined (in the console screen)

The task at hand: Create a two-dimensional array called newArray in the editor. It should have three rows and three columns.

Pop up error I get: Oops, try again. It looks like newArray has fewer than three rows.

This is javscript btw. I don't understand why I get the errors. I am pretty sure my syntax is right.
Maybe this is another problem with the intrepretator. because this works

myArray = new Array();

myArray[0] = "sad";


#2

Hi, @dr.palsonph.d ,

Add this or something equivalent after the newArray declaration ...

newArray.push([]);
newArray.push([]);
newArray.push([]);

Then, newArray[0], newArray[1], and newArray[2] have been defined, and are ready to modify.

EDIT (November 10, 2016):
Are you going to be creating a lot of these Arrays with various sizes? If so, you might want to generalize the process by writing a function. An example follows ...

function matrix_maker(rows, cols) {
  arr = new Array();
  for (i = 0; i < rows; i++) {
    arr.push(new Array());
    for (j = 0; j < cols; j++) {
      arr[i].push(j) ;
    }
  }
  return arr;
}

var newArray = matrix_maker(5, 7)
console.log(newArray);

Output ...

[ [ 0, 1, 2, 3, 4, 5, 6 ],
  [ 0, 1, 2, 3, 4, 5, 6 ],
  [ 0, 1, 2, 3, 4, 5, 6 ],
  [ 0, 1, 2, 3, 4, 5, 6 ],
  [ 0, 1, 2, 3, 4, 5, 6 ] ]

#3

Thank myman!

I just defined my arrays like you suggested (didn't use the .push method, because i dont know what .push does) But i litterly just defined my variables like newArray [0] = new Array();


#4

Also thanks for the neat function, really cool!