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

后端 未结 1 787
旧巷少年郎
旧巷少年郎 2021-01-16 04:50

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?

相关标签:
1条回答
  • 2021-01-16 05:22

    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)

    0 讨论(0)
提交回复
热议问题