简体   繁体   中英

Error : Cannot read property of undefined

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.

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.

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++) {
}

@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM