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?
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.
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!
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(); } } } }
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); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With