简体   繁体   English

错误:无法读取未定义的属性

[英]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. 稍后尝试访问invaldi位置的对象。

It is not matrix that is undefined, but matrix[i]. 未定义的不是矩阵,而是matrix [i]。 Since you are getting your i and j values from jQuery's attribute method, they are strings; 由于您是从jQuery的attribute方法中获取i和j值的,因此它们是字符串。 so before you can use them as indices of your array, you must first convert them to ints: 因此,在将它们用作数组的索引之前,必须首先将它们转换为int:

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. 还要注意,我将第二个参数传递给第一个slice调用,因为您只需要第一个字符。

matrix is an array of length 9 yet your for loops is going 10 times ( i < 10 ). matrix是一个长度为9的数组,但您的for循环要进行10次( 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. jQuery文档的ready函数不需要包装在window.onload事件中。 Also if you have any code that fires before window.onload (because document.ready fires first) then the array will not be populated yet. 同样,如果您有在window.onload之前触发的任何代码(因为document.ready首先触发),那么该数组将不会被填充。 @falinsky is also correct in using var matrix = []; @falinsky在使用var matrix = []时也是正确的; Also view this answer on the difference between [] and new Array() https://stackoverflow.com/a/1273936/2488939 另请查看有关[]与新Array()之间的区别的答案:https://stackoverflow.com/a/1273936/2488939

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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