Question

Error: Uncaught TypeError: Cannot set property '0' of undefined

relevant code:

var field = new Array(6);
for(var x=0; x<field.length; x++){
  field[x] = new Array(12);
  for(var y=0; y<field[x].length; y++){
    field[x][y]= new tile();
    field[x][y].type = Math.floor(Math.random()*7);
    field[x][y].subtype[0]=false;//error happens when I run this line
    field[x][y].subtype[1]=false;
    field[x][y].subtype[2]=false;
    field[x][y].subtype[3]=false;
  }
}


function tile() {
  var type = 0; type = 0;//int
  var subtype = new Array(4);//Boolean

//+ some functions
}

I know that I am missing something, but I don't know what. Any help?

edit: also, when I added "this." before 'type' and 'subtype' in the tile object, I got Uncaught SyntaxError: Unexpected token this edit#2: I got that error because I typed

var this.
//instead of
this.
Was it helpful?

Solution

You need to set your tile properties as just that, member properties by prefixing them with the this keyword, ie

function tile() {
    this.type = 0;
    this.subtype = new Array(4);
}

OTHER TIPS

Just a comment:

To save a lot of typing, you might consider something like:

for(var y=0; y<field[x].length; y++){
  field[x].push(new Tile(Math.floor(Math.random()*7)));
}

and in the constructor:

function Tile(type, subtypes) {
  this.type = type;
  this.subtype = subtypes || [false,false,false,false];
}

so that a new Tile can be initilised with values passed in the call or set to defaults if not.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top