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?
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)