sigil
sigil

Reputation: 9546

"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?

Upvotes: 1

Views: 145

Answers (2)

B. Assem
B. Assem

Reputation: 1078

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.

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386560

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

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

Upvotes: 3

Related Questions