如何访问数组元素的引用(读取和写入数组的元素)



我试图基本上能够访问数组的特定元素,以便读取它或更改它(因此参考思想)。

当然,array[i][j]是解决方案。

但是我试图基本上访问这个元素与特定的ID为每个元素。

让我告诉你我正在努力实现的目标:我想用chessboard.square("a8")访问chessboard[0][0],并能够改变值或读取它。我的2D数组的每个元素都有一个唯一的id(象棋坐标,这里a8代表[0][0]),我发现使用这个id访问元素比编写实际的数组坐标更方便。


square(coordinate) {
const {row, col} = this.parseSquareToBoard(coordinate)  
return this.chessboard[row][col]
}
/* the function parseSquareToBoard is used to get the coordinates of the array from the string id (for example parseSquareToBoard("a8") returns {col: 0, row: 0} */

printBoard() {
this.square('a1') = "R " // this is the line where I obviously get a ReferenceError
this.chessboard.map(row => {
row.map(piece => process.stdout.write(piece ? piece : "X "))
console.log()
})
}

类内部的所有内容。你知道我该怎么做才能做到吗?如果我的问题需要澄清,请告诉我。

感谢

不需要square方法:

const { row, col } = this.parseSquareToBoard(coordinate);
this.chessboard[row][col] = "R ";

如果你真的想避免使用array[i][j],创建一个辅助方法:

setSquare(coordinate, piece) {
const { row, col } = this.parseSquareToBoard(coordinate);
this.chessboard[row][col] = piece;
}
// ...
printBoard() {
this.setSquare("a8", "R ");
// ...
}

最新更新