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

在JavaScript中将对象添加到多维数组,javascript,arrays,html,multidimensional-array,html5-canvas,Javascript,Arrays,Html,Multidimensional Array,Html5 Canvas,我有一个tile对象声明如下: var tile = { x: 0, y: 0, w: canvas.width / numoftiles, h: canvas.width / numoftiles, color: "#FFFFFF" }; 我有一个多维数组来存储这些平铺对象,我这样声明: var tiles = [[]]; 我在画布的长度上循环添加这些瓷砖以填充屏幕,如下所示: for (i = 0; i < (canvas.height /

我有一个tile对象声明如下:

var tile = {
    x: 0,
    y: 0,
    w: canvas.width / numoftiles,
    h: canvas.width / numoftiles,
    color: "#FFFFFF"
};
我有一个多维数组来存储这些平铺对象,我这样声明:

var tiles = [[]];
我在画布的长度上循环添加这些瓷砖以填充屏幕,如下所示:

for (i = 0; i < (canvas.height / numoftiles); i++) {
    for (j = 0; j < (canvas.width / numoftiles); j++) {
        tiles[i][j] = new tile();
    }
}
JavaScript控制台返回“UncaughtTypeError:tile不是构造函数”

如何将平铺对象插入多维数组中的特定位置?

当您执行以下操作时:

var tiles = [[]];
您只创建了
分幅[0]
。为了分配给
tiles[i][j]
tiles[i]
必须是一个数组,但除了
0
之外,它不存在于任何
i
中。您需要在循环中创建子数组

至于您得到的错误,那是因为
tile
只是一个对象,而不是构造函数。如果还没有定义构造函数,只需在循环中指定对象文字即可

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"
        };
    }
}
var tiles=[];
对于(i=0;i<(canvas.height/numoftiles);i++){
瓦片[i]=[];
对于(j=0;j<(canvas.width/numoftiles);j++){
瓷砖[i][j]={
x:0,,
y:0,
w:canvas.width/numoftiles,
h:canvas.width/numoftiles,
颜色:“FFFFFF”
};
}
}
当您执行以下操作时:

var tiles = [[]];
您只创建了
分幅[0]
。为了分配给
tiles[i][j]
tiles[i]
必须是一个数组,但除了
0
之外,它不存在于任何
i
中。您需要在循环中创建子数组

至于您得到的错误,那是因为
tile
只是一个对象,而不是构造函数。如果还没有定义构造函数,只需在循环中指定对象文字即可

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"
        };
    }
}
var tiles=[];
对于(i=0;i<(canvas.height/numoftiles);i++){
瓦片[i]=[];
对于(j=0;j<(canvas.width/numoftiles);j++){
瓷砖[i][j]={
x:0,,
y:0,
w:canvas.width/numoftiles,
h:canvas.width/numoftiles,
颜色:“FFFFFF”
};
}
}

tile
是一个对象文字,您不能在其上使用运算符
new

new
运算符只能在具有构造函数的情况下使用


tile
是一个对象文字,您不能在其上使用运算符
new

new
运算符只能在具有构造函数的情况下使用


您需要定义一个对象构造函数,然后创建构造类型的对象:

function Tile() {
  this.x = 0;
  this.y = 0;
  this.w = canvas.width / numoftiles;
  this.h = canvas.width / numoftiles;
  this.color = "#FFFFFF";
}
现在您可以使用:

var tile = new Tile();

您需要定义对象构造函数,然后创建构造类型的对象:

function Tile() {
  this.x = 0;
  this.y = 0;
  this.w = canvas.width / numoftiles;
  this.h = canvas.width / numoftiles;
  this.color = "#FFFFFF";
}
现在您可以使用:

var tile = new Tile();

tiles[i][j]={}
tiles[i][j]={}使用此解决方案,我的错误仍然存在。JavaScript控制台仍然返回该磁贴不是构造函数。我已将其添加到答案中。使用此解决方案,我的错误仍然存在。JavaScript控制台仍然返回不是构造函数的磁贴。我已经在答案中添加了这一点。