使用以数组为键的 JavaScript Map,为什么我无法获取存储的值?

lbr*_*cel 5 javascript dictionary node.js ecmascript-6

我的代码初始化一个 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)
Run Code Online (Sandbox Code Playgroud)

Cer*_*nce 7

当您将非原始对象传递给 时.get,您需要使用对完全相同对象的.set引用。例如,在设置时,您可以:

  theBoard.set([r, c], '-')
Run Code Online (Sandbox Code Playgroud)

当该行运行时,这会创建一个数组。[r, c]然后,在 中printBoardMap,你的

  let mapKey = [r, c]
Run Code Online (Sandbox Code Playgroud)

创建另一个数组[r, c]。它们不是同一个数组;如果orig是原始数组,mapKey !== orig.

您可以考虑设置和获取字符串,例如'0_2'代替[0, 2]

theBoard.set(r + '_' + c, '-')
Run Code Online (Sandbox Code Playgroud)

const mapKey = r + '_' + c;
Run Code Online (Sandbox Code Playgroud)

(最好使用const,并且let尽可能不要使用 - 仅let当您需要重新分配相关变量时才使用)