1

I can't seem to fix this problem. My code is as follows:

var matrix = [];

// initialise the grid:
window.onload = function(){

    var cells ='';

    for(var i = 0; i < 10; i++){

        matrix[i] = [];

        for (var j = 0; j < 10; j++){

            matrix[i][j] = "white";

            cells += "<span class = 'cell' id='cell"+ i + "" + j + "' onClick = 'toggleCell("+i+","+j+")' ></span>";

        }
    }
        $('#grid-container').html(cells);

}

When I try to call elements of matrix in other methods, I get undifined.

SOLVED

  • tried to access objects at invaldi positions later on.
Radu B
  • 47
  • 9
  • 7
    you do not need to wrap a jquery ready call in the windows onload event. – Patrick Evans Mar 18 '14 at 01:13
  • 1
    When selecting the `document`, don't quote it. Just pass [the variable](https://developer.mozilla.org/en-US/docs/Web/API/Window.document): `$(document).ready(...)`. When quoted, it's instead an [element selector](http://api.jquery.com/element-selector/) trying to find `` elements. – Jonathan Lonowski Mar 18 '14 at 01:18
  • 1
    @JonathanLonowski While I completely agree, I'm just saying - for the `.ready()` method, it doesn't matter what the selector is – Ian Mar 18 '14 at 01:23
  • whether the other methods are called after window load event – Arun P Johny Mar 18 '14 at 01:25
  • [Learn how to debug JavaScript](http://www.creativebloq.com/javascript/javascript-debugging-beginners-3122820), set a breakpoint, inspect variables. If the elements ID is `cell15`, then `i` becomes `15` and `j` becomes `5`. That's probably not what you want. You probably want `var i = $(this).attr('id').slice(-2, -1);` – Felix Kling Mar 18 '14 at 01:55

3 Answers3

1

It is not matrix that is undefined, but matrix[i]. Since you are getting your i and j values from jQuery's attribute method, they are strings; so before you can use them as indices of your array, you must first convert them to ints:

var i = parseInt($(this).attr('id').slice(-2, -1), 10);
var j = parseInt($(this).attr('id').slice(-1), 10);

Notice, also, that I passed a second argument to the first slice call because you want only the first character.

76484
  • 8,498
  • 3
  • 19
  • 30
0

matrix is an array of length 9 yet your for loops is going 10 times (i < 10). Change your loop to something like:

for( var i = 0; i < matrix.length; i++) {
}
Fizz
  • 3,427
  • 4
  • 27
  • 43
0

@Patrick Evans is right. The jQuery document ready function does not need to be wrapped in the window.onload event. Also if you have any code that fires before window.onload (because document.ready fires first) then the array will not be populated yet. @falinsky is also correct in using var matrix = []; Also view this answer on the difference between [] and new Array() https://stackoverflow.com/a/1273936/2488939

Community
  • 1
  • 1
The Mahahaj
  • 696
  • 6
  • 8