最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cannot set property '0' of undefined - Stack Overflow

programmeradmin5浏览0评论

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.

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;

Please ask if you need more information!

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.

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;

Please ask if you need more information!

Share Improve this question edited Aug 12, 2013 at 4:49 Erik Philips 54.7k11 gold badges131 silver badges156 bronze badges asked Aug 12, 2013 at 4:47 lewisjblewisjb 68610 silver badges26 bronze badges 1
  • why did you do it like, thisInstance[1][0] = 1;. thisInstance is a Grid object. thisInstance[1] does not refer to anything here. – schnill Commented Aug 12, 2013 at 5:01
Add a ment  | 

2 Answers 2

Reset to default 6

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

Replace

thisInstance[1][0] = 1;

by

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

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

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'.

发布评论

评论列表(0)

  1. 暂无评论