简体   繁体   中英

“Cannot set property of undefined”, even though array has already been initialized

I want to create a 2D array of objects, and then set the value of one element's property.

var maze=new Maze(3);
maze.resetField();

function Maze(size){
    this.size=size;
    this.xPos=0;
    this.yPos=0;
    this.field=[];
    this.resetField=function(){
        this.field=[];
        this.xPos=0;
        this.yPos=0;
        var row;
        var newWord;
        var newPlace;
        for(rowCtr=0;rowCtr<this.size;rowCtr++){
            row=[];
            for(r=0;r<this.size;r++){
                newWord="rowCtr"+rowCtr+"r"+r;
                newPlace=Place(newWord);
                row[r]=newPlace;
            }
            this.field.push(row);
        }
        treasureX=1;
        treasureY=1;
        this.field[treasureY][treasureX].word="treasure";
    }

}

function Place(word){
    this.word=word;
    this.walls=[];
    this.addWall=function(route){
        this.walls.add(route);
    }
}

When the code reaches this line:

this.field[treasureY][treasureX].word="treasure";

I get this error:

Uncaught TypeError: Cannot set property 'word' of undefined

But since I've already initialized all the array elements with the nested for loops, shouldn't this.field[treasureY][treasureX] already be defined as an instance of Place ?

I suggest to use new for a new instance of Place .

newPlace = new Place(newWord);
//         ^^^

You must replace:

newPlace=Place(newWord);

by

newPlace=new Place(newWord);

If you don't use the new keyword, the variable newPlace will be set to undefined, so all your array elements will be undefined.

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