Using a JavaScript Map with array as key, why can't I get the stored value?

浪子不回头ぞ 提交于 2020-12-26 04:37:09

问题


My code initializes a Map object and uses arrays as key. When I try to use the map.get() method, I get "undefined" instead of the value I expect. What am I missing?

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)

回答1:


When you pass in a non-primitive to .get, you need to have used .set with a reference to the exact same object. For example, while setting, you do:

  theBoard.set([r, c], '-')

This creates an array [r, c] when that line runs. Then, in printBoardMap, your

  let mapKey = [r, c]

creates another array [r, c]. They're not the same array; if orig were the original array, mapKey !== orig.

You might consider setting and getting strings instead, for example '0_2' instead of [0, 2]:

theBoard.set(r + '_' + c, '-')

and

const mapKey = r + '_' + c;

(best to use const and not let when possible - only use let when you need to reassign the variable in question)



来源:https://stackoverflow.com/questions/53367770/using-a-javascript-map-with-array-as-key-why-cant-i-get-the-stored-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!