Program Club

Typescript-다차원 배열 초기화

proclub 2020. 12. 8. 20:12
반응형

Typescript-다차원 배열 초기화


나는 Typescript를 가지고 놀고 있는데 어떻게 다차원 배열을 적절하게 인스턴스화하고 선언하는지 궁금합니다. 내 코드는 다음과 같습니다.

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 ???
            }
        }
    }
}

선택한 장소에 대한 힌트를 줄 수 있습니까?


당신은 필요가 []이 유형에 상관없이 사실입니다 - 배열을 인스턴스화 할 수 있습니다. 배열이 배열 유형이라는 사실은 중요하지 않습니다.

루프의 첫 번째 수준에서도 동일한 사항이 적용됩니다. 그것은 단순한 배열이며 []새로운 빈 배열입니다.

두 번째 수준에 관해서 Thing는 클래스라면 new Thing()괜찮을 것입니다. 그렇지 않으면 유형에 따라 팩토리 함수 또는 다른 표현식이 필요할 수 있습니다.

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

당신이 그것을 입력하고 싶다면 :

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

다음은 boolean [] [] 초기화의 예입니다.

const n = 8; // or some dynamic value
const palindrome: boolean[][] = new Array(n).fill(false).map(() => new Array(n).fill(false));

Beware of the use of push method, if you don't use indexes, it won't work!

var main2dArray: Things[][] = []

main2dArray.push(someTmp1dArray)
main2dArray.push(someOtherTmp1dArray)

gives only a 1 line array!

use

main2dArray[0] = someTmp1dArray
main2dArray[1] = someOtherTmp1dArray

to get your 2d array working!!!

Other beware! foreach doesn't seem to work with 2d arrays!

참고URL : https://stackoverflow.com/questions/30144580/typescript-multidimensional-array-initialization

반응형