0

So I want to check a spot in a two-dimensional array, but I have no idea why chrome returns:

"Uncaught TypeError: Cannot read property '0' of undefined".

In function put() I check if fieldSpaces[column][row] is equal to empty

This is my JS-code:

var empty = 0;

var fieldSpaces = new Array(7);
for (var column = 0; column < 7; column++)
    fieldSpaces[column] = new Array(6);

for (var column = 0; column < 7; column++)
    for (var row = 0; row < 6; row++)
        fieldSpaces[column][row] = empty;

function checkEmpty(c){
    var top = 5;
    var column = c;
    var isEmpty = false;
    if(fieldSpaces[column][0] == empty){
        console.log("It is empty");
    }
}
  • No console errors, `checkEmpty(0);` returns `It is empty`. I can't see or replicate the issue. – Tim Lewis Jun 04 '15 at 16:28
  • When you call `checkEmpty` what is the argument you are passing to it? Also, it might help to see the source for the `put` function you mentioned. – neuronaut Jun 04 '15 at 16:29
  • What are you passing as c? – Zee Jun 04 '15 at 16:29
  • `c` is a column, should be a number, but missing in source question. – Tim Lewis Jun 04 '15 at 16:31
  • Unless you want to test only numbers you know exist as an index of `fieldSpaces` you should check if `fieldSpace[column]` exist before trying to access it as an array. In the sample provided only numbers between 0 and 6 included can be tested, otherwise an error would be generated. – GillesC Jun 04 '15 at 16:32
  • You can check for needles in JavaScript arrays in different ways, maybe the following link can help you? http://stackoverflow.com/questions/784012/javascript-equivalent-of-phps-in-array – Fredrik Borggren Jun 04 '15 at 16:35
  • As an aside: you are essentially iterating over the containing array twice. You could combine the two for loops (similar to your existing second loop) or you could use something like: `var fieldSpaces = Array(6).join('.').split('.').map(function() {return Array(5).join('.').split('.').map(function() {return empty;});});`. – Jason Cust Jun 04 '15 at 16:37
  • I think I might have fixed it while I was making the comment and while I was shrinking the code for only the error. Thanks all for the help! – Jonathan de Geus Jun 04 '15 at 18:09

0 Answers0