【问题标题】:How do I declare a Multidimensional Array of a given size in Typescript如何在 Typescript 中声明给定大小的多维数组
【发布时间】:2016-09-10 15:53:28
【问题描述】:

我有以下...

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?
  }
  ...
}

如何在 Typescript 中声明这样的内容?

错误是...

无法读取未定义的属性“2”

【问题讨论】:

    标签: javascript multidimensional-array typescript


    【解决方案1】:

    没有办法(据我所知)在一行中用 javascript 实例化一个多维数组。 您必须自己实际创建所有数组,例如:

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

    【讨论】:

    • 如果按照我上面的方式输入怎么办?
    • 它适用于我的代码。您有问题或错误吗?
    猜你喜欢
    • 2020-03-06
    • 1970-01-01
    • 1970-01-01
    • 2012-03-12
    • 2021-09-28
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多