无法设置未定义的属性“0”

时间:2022-01-07 09:09:49

I have checked other questions with the same problem, but they don't work for mine.

我已经检查了同样问题的其他问题,但它们对我的工作不起作用。

I am getting the error: Cannot set property '0' of undefined with my JavaScript; I am using Google Chrome.

我收到错误:无法使用我的JavaScript设置未定义属性'0';我正在使用Google Chrome。

var thisInstance = new Grid(100,100);
thisInstance.initGrid();

function Grid(maxX, maxY) {
    this.grid     = new Array();
    this.gridMaxX = maxX;
    this.gridMaxY = maxY;

    this.initGrid = function() {
        for(var i = 0; i < this.gridMaxX; i++) {
            this.grid[i] = new Array();
        }
    }
}

And I get the error when I call: thisInstance[1][0] = 1;

我打电话时收到错误:thisInstance [1] [0] = 1;

Please ask if you need more information!

请询问您是否需要更多信息!

2 个解决方案

#1


6  

The error is fired because you are trying to access [0] on an undefined object.

由于您尝试访问未定义对象上的[0],因此会触发该错误。

Replace

thisInstance[1][0] = 1;

by

thisInstance.grid[1][0] = 1;

thisInstance is just an instance of Grid, not an array.

thisInstance只是Grid的一个实例,而不是数组。

#2


-1  

In this part of the code:

在这部分代码中:

this.initGrid = function() {
    for(var i = 0; i < this.gridMaxX; i++) {
        this.grid[i] = new Array();
    }
}

this.initGrid and this.grid do not refer to the same object 'this'.

this.initGrid和this.grid不引用同一个对象'this'。

#1


6  

The error is fired because you are trying to access [0] on an undefined object.

由于您尝试访问未定义对象上的[0],因此会触发该错误。

Replace

thisInstance[1][0] = 1;

by

thisInstance.grid[1][0] = 1;

thisInstance is just an instance of Grid, not an array.

thisInstance只是Grid的一个实例,而不是数组。

#2


-1  

In this part of the code:

在这部分代码中:

this.initGrid = function() {
    for(var i = 0; i < this.gridMaxX; i++) {
        this.grid[i] = new Array();
    }
}

this.initGrid and this.grid do not refer to the same object 'this'.

this.initGrid和this.grid不引用同一个对象'this'。