如何在 typescript 中定義二維array
自行定義一個 Matrix 2d array
2d array內只能放自己定義的cell物件
定義一個 type 叫做 Matrixtype 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);
1.type 命名約定成俗都是 大寫駝峰
2.你原本寫法是不能產出 matrix的要多一個 cellarry
產出裡面的陣列
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)
舉幾個例子:
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' }],
];