【发布时间】:2020-12-26 03:55:18
【问题描述】:
我在尝试将对象推送到来自二维数组的数组时遇到问题。
let blacksPosition: Array<any>;
for (let i = 0; i < 8; i++) {
for (let j = 0; j < 8; j++) {
if (boardArray[i][j].team === "black") {
blacksPosition.push(boardArray[i][j]);
}
}
}
TypeScript 给我以下错误:
变量“blacksPosition”在被赋值之前使用。
但我之前没有使用过blacksPosition。这是我第一次在该行中声明它。
boardArray 是使用以下函数创建的二维数组:
function create2DArray(rows: number, cols: number): Array<Array<any>> {
const arr = new Array(rows);
for (let i = 0; i < arr.length; i++) {
arr[i] = new Array(cols);
}
return arr;
}
然后我用 Tile 对象填充这个二维数组:
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
boardArray[i][j] = new Tile(i, j, col, "none");
}
}
这是 Tile 类:
class Tile {
x: number;
y: number;
tile: Element;
team: string;
piece: string;
constructor(i: number, j: number, tile: Element, team: string) {
this.x = i;
this.y = j;
this.tile = tile;
this.piece = "none";
this.team = team;
}
}
有没有办法将那些来自 2D 数组的 Tile 对象添加到 blacksPosition 数组?
【问题讨论】:
-
就像错误告诉你的那样,你给了它一个类型但没有空数组值
标签: javascript arrays typescript loops multidimensional-array