0

I have a tile object declared as follows:

var tile = {
    x: 0,
    y: 0,
    w: canvas.width / numoftiles,
    h: canvas.width / numoftiles,
    color: "#FFFFFF"
};

I have a multidimensional array to store a number of these tile objects, which I declare like so:

var tiles = [[]];

I loop through the length of my canvas adding these tiles to fill the screen like so:

for (i = 0; i < (canvas.height / numoftiles); i++) {
    for (j = 0; j < (canvas.width / numoftiles); j++) {
        tiles[i][j] = new tile();
    }
}

My error occurs on the line:

tiles[i][j] = new tile();

The JavaScript console returns "Uncaught TypeError: tile is not a constructor"

How can I insert tile objects to a specific location in my multidimensional array?

user163505
  • 481
  • 3
  • 11
  • 22

3 Answers3

1

When you do:

var tiles = [[]];

you've only created tiles[0]. In order to assign to tiles[i][j], tiles[i] has to be an array, but it doesn't exist for any i other than 0. You need to create the sub-arrays in your loop.

As for the error you're getting, that's because tile is just an object, not a constructor function. If you haven't defined a constructor, just assign the object literal in the loop.

var tiles = [];
for (i = 0; i < (canvas.height / numoftiles); i++) {
    tiles[i] = [];
    for (j = 0; j < (canvas.width / numoftiles); j++) {
        tiles[i][j] = {
            x: 0,
            y: 0,
            w: canvas.width / numoftiles,
            h: canvas.width / numoftiles,
            color: "#FFFFFF"
        };
    }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

You need to define an object constructor, and then create objects of the constructed type:

function Tile() {
  this.x = 0;
  this.y = 0;
  this.w = canvas.width / numoftiles;
  this.h = canvas.width / numoftiles;
  this.color = "#FFFFFF";
}

Now you can use:

var tile = new Tile();
HySoaKa
  • 56
  • 5
0

tile is an object literal, you can not use the operator new on it.

new operator can only be used if you have a constructor function.

This SO has good explanation about how to clone objects:

Community
  • 1
  • 1
Klinger
  • 4,900
  • 1
  • 30
  • 35