如何在Typescript中声明给定大小的多维数组

时间:2016-09-10 15:53:29

标签: javascript multidimensional-array typescript

我有以下......

export class Puzzle {
  pieces : Piece[];
  orderedPieces : Piece[][];
  constructor(width: number, height: number){
    this.height = height, this.width = width;
    let total : number = width * height;
    this.pieces = new Array<Piece>(total);
    this.orderedPieces = new Piece[height][width]; // Doesn't work what do I put here?
  }
  ...
}

我如何在打字稿中声明这样的东西?

错误是......

  

无法阅读财产&#39; 2&#39;未定义的

1 个答案:

答案 0 :(得分:1)

我无法(我知道)在一行中在javascript中实例化多维数组。 您必须自己创建所有数组,例如:

this.orderedPieces = new Array(this.height);

for (let i = 0; i < this.height; i++) {
    this.orderedPieces[i] = new Array(this.width);
}