Reputation: 9546
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
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
Reputation: 386560
I suggest to use new
for a new instance of Place
.
newPlace = new Place(newWord);
// ^^^
Upvotes: 3