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

5

我的代码初始化了一个 Map 对象,并使用数组作为键。当我尝试使用 map.get() 方法时,我得到的是"undefined" ,而不是我期望的值。我漏掉了什么?

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个回答

7

当你传递一个非原始类型的参数给.get时,你需要使用.set并将其设置为指向完全相同的对象。例如,在设置过程中,你需要这样做:

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

这行代码运行时会创建一个数组[r,c]。接下来,在printBoardMap中,您可以使用该数组。
  let mapKey = [r, c]

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

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

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

并且

const mapKey = r + '_' + c;

在可能的情况下最好使用 const 而不是 let - 仅在需要重新分配变量时使用 let


谢谢CertainPerformance,我觉得这是一个值与引用的问题。我看到我可以使用字符串来解决它。如果我能使用数组或对象就好了,但似乎除非键是原始类型,否则无法随机访问Map条目? - lbrucel
好的,我想另一种方法是创建另一个Map,从'#_#'字符串获取(单数)[r,c]数组,但这只是在不必要的抽象层面上解决了同样的问题。 - CertainPerformance
我开始尝试解构这个redux代码[https://github.com/DatGreekChick/tic-tac-toe],它使用_immutable_ Map作为棋盘数据结构。现在我看到它坚持使用原始数据类型(数字)作为键。最终它创建了这个: Map { 0: Map { 0: "X", 1: "O", 2: "X" }, 2: Map { 0: "O", 1: "X", 2: "O" }, 1: Map { 0: "X", 1: "O", 2: "X" } } - lbrucel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接