我的代码初始化了一个 Map 对象,并使用数组作为键。当我尝试使用 map.get() 方法时,我得到的是"undefined" ,而不是我期望的值。我漏掉了什么?
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)
Map
,从'#_#'
字符串获取(单数)[r,c]
数组,但这只是在不必要的抽象层面上解决了同样的问题。 - CertainPerformance