0

I am making an array of array (a grid) in typescript. I need this array to be 5x4. I am trying to understand how to instantiate it. I know I can do like this for a one dimension array:

let myvar:string[]=new Array(3);

I tried that way but it didn't work when I am trying to push an element. It is saying that my array has 0 line.

export class grid {

    public mainGrid: string[][];

public constructor() {

        this.mainGrid = new Array<Array<string>(5)>(4);
    }

}

Or should I push a new Array(5) for times?

  • 2
    Possible duplicate of [Typescript - multidimensional array initialization](http://stackoverflow.com/questions/30144580/typescript-multidimensional-array-initialization) – devlin carnate Aug 19 '16 at 20:02
  • So I can't initiate the 2 array in one sentence? – John Doe the Doe Aug 19 '16 at 20:03
  • well, you could, but it wouldn't be pretty or extensible – Kevin B Aug 19 '16 at 20:04
  • So 1st I instantiate the this.mainGrid = new Array>(); then I loop and push new Array()? – John Doe the Doe Aug 19 '16 at 20:09
  • Javascript (and typescript) doesn't have multidimensional arrays. Typically, arrays of arrays are used instead. Indeed, you'd create a `string[][]`, and iterate once to create each inner array. – recursive Aug 19 '16 at 20:12
  • @recursive array of array is the same as a multi dimensional array. How are you distinguishing the two ? It's the same thing from a logic point of view. Btw nice profile :) – Ced Aug 19 '16 at 20:37
  • 1
    @Ced: They are different. For example. An array of arrays can contain rows that are different lengths. – recursive Aug 19 '16 at 20:40

1 Answers1

-2

In JS you could do something like:

let elem = 0;//
let arr1 = [elem,elem,elem,elem];
let arr2 = [elem,elem,elem,elem];
let arr3 = [elem,elem,elem,elem];
let arr4 = [elem,elem,elem,elem];
let arr5 = [elem,elem,elem,elem];
let grid = [arr1, arr2, arr3, arr4, arr5];

but you will have to control that the length is not surpassed...

DIEGO CARRASCAL
  • 1,999
  • 14
  • 16