我的代码初始化Map对象,并使用数组作为键。当我尝试使用map.get()方法时,得到的是“未定义”而不是我期望的值。我想念什么?
const initBoardMap = () => {
let theBoard = new Map()
for (let r = 0; r < 3; r++) {
for (let c = 0; c < 3; c++) {
//create a Map and set keys for each entry an array [r,c]
//set the value to a dash
// ---- commented out the array as key :-(
//theBoard.set([r, c], '-')
const mykeyStr = r + ',' + c
theBoard.set(mykeyStr, '-')
}
}
return theBoard
}
const printBoardMap = theBoard => {
for (let r = 0; r < 3; r++) {
let row=''
for (let c = 0; c < 3; c++) {
//initialize an array as the map key
// comment out array as key
// let mapKey = [r, c]
//
//why can't I get the value I expect from the line below?
//
//let square = theBoard.get(mapKey)
//log the value of map.get --- notice its always undefined
const mykeyStr = r + ',' + c
row += theBoard.get(mykeyStr)
if (c < 2) row += '|'
}
console.log(row)
}
}
let boardMap = initBoardMap()
printBoardMap(boardMap)
答案 0 :(得分:2)
当您将非基元传递给.get
时,您需要使用.set
来引用完全相同的对象。例如,在设置时,您可以执行以下操作:
theBoard.set([r, c], '-')
该行运行时,此创建数组[r, c]
。然后,在printBoardMap
中,您的
let mapKey = [r, c]
创建另一个数组[r, c]
。它们不是同一阵列;如果orig
是原始数组,则mapKey !== orig
。
您可以考虑改为设置并获取字符串,例如'0_2'
代替[0, 2]
:
theBoard.set(r + '_' + c, '-')
和
const mapKey = r + '_' + c;
(最好使用const
而不是let
-仅在需要重新分配有问题的变量时使用let
)