Jackie
Jackie

Reputation: 23509

How do I declare a Multidimensional Array of a given size in Typescript

I have the following...

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

How would I declare something like this in Typescript?

Error is...

Cannot read property '2' of undefined

Upvotes: 0

Views: 2534

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164139

There's no way (that I'm aware of) to instantiate a multidimensional array in javascript in one line. You'll have to actually create all of the arrays yourself, something like:

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

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

Upvotes: 1

Related Questions