Search code examples
multidimensional-arraytypescript

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?


Solution

  • 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();
                }
            }
        }
    }