iT邦幫忙

0

typescript 自定義2維 array的方式?

  • 分享至 

  • xImage

如何在 typescript 中定義二維array

自行定義一個 Matrix 2d array
2d array內只能放自己定義的cell物件

定義一個 type 叫做 Matrix
type Matrix = Array<cell>[][];
這樣是正確的嗎?

下面是code:

type coord = {
  nCol: number;
  nRow: number;
  pCol: number;
  pRow: number;
};

type cell = {
  coord: coord;
  value: number;
  move: boolean;
  merger: boolean;
};

type Matrix = Array<cell>[][];

let matrix: Matrix = [];
// 錯誤
// Cannot redeclare block-scoped variable 'matrix'

// 往2d array塞入資料
for (let i = 0; i < 4; i++) { // 行
  for (let j = 0; j < 4; j++) { // 列
    let coord: coord = {
      nCol: i,
      nRow: j,
      pCol: i,
      pRow: j,
    };
    let cell: cell = {
      coord: coord,
      value: 20,
      move: false,
      merger: false,
    };
    matrix[i][j] = cell;
    // 錯誤
    // Type 'cell' is missing the following properties from type 'cell[]': length, pop, push, concat, and 28 more.ts(2740)
  }
}

console.log(matrix);
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
0
前端野人
iT邦新手 3 級 ‧ 2022-07-24 14:30:08
最佳解答

1.type 命名約定成俗都是 大寫駝峰
2.你原本寫法是不能產出 matrix的要多一個 cellarry產出裡面的陣列

Demo

type Coord = {
    nCol: number;
    nRow: number;
    pCol: number;
    pRow: number;
}

type Cell = {
    coord: Coord;
    value: number;
    move: boolean;
    merger: boolean;
}

type Matrix = Cell[][]

const convertMatrix = (rows: number, cells: number) => {
    let matrix: Matrix = []
    for (let i = 0; i < rows; i++) {
        let cellarray: Cell[] = []
        for (let j = 0; j < cells; j++) {
            let coord: Coord = {
                nCol: i,
                nRow: j,
                pCol: i,
                pRow: j,
            };
            let cell: Cell = {
                coord: coord,
                value: 20,
                move: false,
                merger: false,
            };
            cellarray[j] = cell
        }
        matrix[i] = cellarray
    }
    return matrix
}

const matrix = convertMatrix(4, 4)

console.log(matrix)

感恩

0
HAO
iT邦研究生 3 級 ‧ 2022-07-22 19:45:23

你好,二維陣列的話是這樣:

type Matrix = cell[][];
0
harry xie
iT邦研究生 1 級 ‧ 2022-07-23 09:27:55

舉幾個例子:

const arr: string[][] = [['one'], ['two']]; // 含初始化的值

const arr2: number[][] = []; // 不含

type Employee = {
  id: number;
  name: string;
};

const arr3: Employee[][] = [ // 搭配 type 使用
  [{ id: 1, name: 'Alice' }],
  [{ id: 2, name: 'Bob' }],
];

我要發表回答

立即登入回答