【发布时间】:2018-11-19 03:05:51
【问题描述】:
我的代码初始化一个 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)
【问题讨论】:
标签: javascript node.js dictionary ecmascript-6