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?

7
  • 2
    Possible duplicate of Typescript - multidimensional array initialization Commented Aug 19, 2016 at 20:02
  • So I can't initiate the 2 array in one sentence? Commented Aug 19, 2016 at 20:03
  • well, you could, but it wouldn't be pretty or extensible Commented Aug 19, 2016 at 20:04
  • So 1st I instantiate the this.mainGrid = new Array<Array<string>>(); then I loop and push new Array<string>()? Commented Aug 19, 2016 at 20:09
  • 1
    @Ced: They are different. For example. An array of arrays can contain rows that are different lengths. Commented Aug 19, 2016 at 20:40

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.