填充多维枚举数组

时间:2018-03-08 13:36:20

标签: angular typescript multidimensional-array

我正在尝试填充enums的多维数组,但我遇到了一些麻烦。

以下代码尽可能接近,但数组的类型为number,而不是enum类型TileAssignment

以下是我的代码段:

board.ts

import { TileAssignment } from './tile-assignment.enum';

export class Board {

  width: number;
  height: number;
  boardTiles: TileAssignment[][];

  static fromJsonObj(boardObj: object): Board {

    const tiles = new Array<Array<TileAssignment>>();

    for (let i = 0; i < boardObj['BoardTiles'].length; i++) {
      const row: TileAssignment[]  = new Array<TileAssignment>();
      for (let y = 0; y < boardObj['BoardTiles'][i].length; y++) {
        const t = boardObj['BoardTiles'][i][y]['TileAssignment'];
        row.push(t);
        // row.push(TileAssignment[t]) pushes string
      }
      tiles.push(row);
    }

    return new Board(boardObj['Width'], boardObj['Height'], tiles)
  }

  constructor(w: number, h: number, tiles: TileAssignment[][]) {
    this.width = w;
    this.height = h;
    this.boardTiles = tiles;
  }
}

瓦片assignment.enum.ts:

export enum TileAssignment {
  Free,
  Mine,
  Exit
}

boardObj:

{
  "BoardTiles": [
    [
      {
        "TileAssignment": 0
      },
      {
        "TileAssignment": 0
      },
      {
        "TileAssignment": 0
      },
      {
        "TileAssignment": 0
      }
    ],
    [
      {
        "TileAssignment": 0
      },
      {
        "TileAssignment": 1
      },
      {
        "TileAssignment": 0
      },
      {
        "TileAssignment": 0
      }
    ],
    [
      {
        "TileAssignment": 0
      },
      {
        "TileAssignment": 0
      },
      {
        "TileAssignment": 0
      },
      {
        "TileAssignment": 0
      }
    ],
    [
      {
        "TileAssignment": 0
      },
      {
        "TileAssignment": 1
      },
      {
        "TileAssignment": 0
      },
      {
        "TileAssignment": 1
      }
    ],
    [
      {
        "TileAssignment": 0
      },
      {
        "TileAssignment": 0
      },
      {
        "TileAssignment": 2
      },
      {
        "TileAssignment": 0
      }
    ]
  ]
}

我是否正确地将值分配给我的数组还是有其他方法吗?

1 个答案:

答案 0 :(得分:0)

看起来您应该比boardObject更强烈地键入object参数。怎么样:

export interface BoardObject {
  Width: number,
  Height: number,
  BoardTiles: { TileAssignment: TileAssignment }[][]
}

export class Board {
  static fromJsonObj(boardObj: BoardObject): Board {
  // ⋮      
  }
// ⋮
}

请注意,boardObj示例缺少必需的WidthHeight属性。这对你有用还是有其他问题?

祝你好运。