Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - multidimensional array initialization

I'm playing with Typescript and I wonder, how to properly instantiate and declare multidimensional array. Here's my code:

class Something {     private things: Thing[][];      constructor() {         things = [][]; ??? how instantiate object ???          for(var i: number = 0; i < 10; i++) {             this.things[i] = new Thing[];   ??? how instantiate 1st level ???             for(var j: number = 0; j< 10; j++) {                 this.things[i][j] = new Thing();   ??? how instantiate 2nd lvl item ???             }         }     } } 

Can you give me any hint about selected places?

like image 769
Fka Avatar asked May 09 '15 20:05

Fka


People also ask

How do I create a multidimensional array in TypeScript?

To declare a two-dimensional array, set the type of the array as Type[][] , e.g. const arr: string[][] = [['one'], ['two']] . You can read the type as an array containing arrays of specific type.

How do I create an array of objects in TypeScript?

To declare an array of objects in TypeScript, set the type of the variable to {}[] , e.g. const arr: { name: string; age: number }[] = [] . Once the type is set, the array can only contain objects that conform to the specified type, otherwise the type checker throws an error. Copied!


2 Answers

You only need [] to instantiate an array - this is true regardless of its type. The fact that the array is of an array type is immaterial.

The same thing applies at the first level in your loop. It is merely an array and [] is a new empty array - job done.

As for the second level, if Thing is a class then new Thing() will be just fine. Otherwise, depending on the type, you may need a factory function or other expression to create one.

class Something {     private things: Thing[][];      constructor() {         this.things = [];          for(var i: number = 0; i < 10; i++) {             this.things[i] = [];             for(var j: number = 0; j< 10; j++) {                 this.things[i][j] = new Thing();             }         }     } } 
like image 53
Puppy Avatar answered Sep 28 '22 06:09

Puppy


If you want to do it typed:

class Something {    areas: Area[][];    constructor() {     this.areas = new Array<Array<Area>>();     for (let y = 0; y <= 100; y++) {       let row:Area[]  = new Array<Area>();             for (let x = 0; x <=100; x++){         row.push(new Area(x, y));       }       this.areas.push(row);     }   } } 
like image 24
RMuesi Avatar answered Sep 28 '22 06:09

RMuesi