简体   繁体   English

在JavaScript中将对象添加到多维数组

[英]Adding an object to a multidimensional array in JavaScript

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" JavaScript控制台返回“ Uncaught TypeError:tile不是构造函数”

How can I insert tile objects to a specific location in my multidimensional array? 如何在我的多维数组中的特定位置插入图块对象?

When you do: 当您这样做时:

var tiles = [[]];

you've only created tiles[0] . 您只创建了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 . 为了分配给tiles[i][j]tiles[i]必须是一个数组,但除0以外的任何i都不存在。 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. 至于得到的错误,那是因为tile只是一个对象,而不是构造函数。 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"
        };
    }
}

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();

tile is an object literal, you can not use the operator new on it. tile是对象文字,您不能在其上使用new运算符。

new operator can only be used if you have a constructor function. 如果您有构造函数,则只能使用new运算符。

This SO has good explanation about how to clone objects: 该SO很好地解释了如何克隆对象:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM