[英]How to access the reference of an array element (read & write the element of an array)
I am trying to basically being able to access a specific element of an array in order to read it or to change it (thus the reference idea).我试图基本上能够访问数组的特定元素以便读取或更改它(因此参考想法)。
Sure, array[i][j]
is the solution.当然,
array[i][j]
是解决方案。
But I am trying to basically access this element with a specific ID for each element.但是我试图基本上使用每个元素的特定 ID 来访问这个元素。
Let me show you what I am trying to achieve: I want to access chessboard[0][0]
with chessboard.square("a8")
and be able to change the value or read it.让我向您展示我想要实现的目标:我想使用
chessboard.square("a8")
访问chessboard[0][0]
并能够更改值或读取它。 Each element of my 2D array has an unique id (the chess coordinates, here a8 for [0][0]) and I would find it more convenient to access the element with this ID rather than write the actual array coordinates.我的 2D 数组的每个元素都有一个唯一的 ID(国际象棋坐标,这里是 [0][0] 的 a8),我会发现使用这个 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()
})
}
All that is inside a class. Any idea of what I could do to be able to do so?所有这些都在 class 中。知道我可以做什么才能做到这一点吗? Please let me know if my question needs clarification.
如果我的问题需要澄清,请告诉我。
Thanks谢谢
No need for a square
method:不需要
square
方法:
const { row, col } = this.parseSquareToBoard(coordinate);
this.chessboard[row][col] = "R ";
If you really want to avoid using array[i][j]
, make a helper method:如果你真的想避免使用
array[i][j]
,制作一个辅助方法:
setSquare(coordinate, piece) {
const { row, col } = this.parseSquareToBoard(coordinate);
this.chessboard[row][col] = piece;
}
// ...
printBoard() {
this.setSquare("a8", "R ");
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.