簡體   English   中英

在JavaScript中將對象添加到多維數組

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

我有一個磁貼對象聲明如下:

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

我的錯誤發生在行上:

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

JavaScript控制台返回“ Uncaught TypeError:tile不是構造函數”

如何在我的多維數組中的特定位置插入圖塊對象?

當您這樣做時:

var tiles = [[]];

您只創建了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"
        };
    }
}

您需要定義一個對象構造函數,然后創建構造類型的對象:

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

tile是對象文字,您不能在其上使用new運算符。

如果您有構造函數,則只能使用new運算符。

該SO很好地解釋了如何克隆對象:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM