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?

1
  • tiles[i][j] = {}; Commented Dec 24, 2016 at 0:43

3 Answers 3

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();
Sign up to request clarification or add additional context in comments.

Comments

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"
        };
    }
}

2 Comments

My error still persists using this solution. The JavaScript console still returns that tile is not a constructor.
I've added that to the answer.
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:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.