gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:17:18 24 4
gpt4 key购买 nike

我的代码初始化一个 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)

最佳答案

当您将非基本类型传递给 .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 )

关于javascript - 使用以数组为键的 JavaScript Map,为什么我无法获取存储的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53367770/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com