使用 JavaScript 地图时,如何解决“.has 不是函数”的错误?
How do I fix the error '.has is not a function' when using JavaScript Map?
我有以下尝试在地图中设置值的代码:
class Trie {
constructor () {
this.trie = new Map()
}
insert(word) {
let current = this.trie
for (let alpha of word) {
if (!current.has(alpha)) current.set(alpha, [])
current = current.get(alpha)
}
current.word = word
}
}
let trie = new Trie()
trie.insert('test')
console.log(trie.trie)
当我尝试 运行 它时,出现错误 .has is not a function
。我在这里错过了什么?
您正在将 current
重新分配给循环内的非 Map 值,因此在后续迭代中,current.has
将不起作用。听起来您需要将 []
改为 new Map
。
class Trie {
constructor () {
this.trie = new Map()
}
insert(word) {
let current = this.trie
for (let alpha of word) {
if (!current.has(alpha)) current.set(alpha, new Map())
current = current.get(alpha)
}
current.word = word
}
}
let trie = new Trie()
trie.insert('test')
console.log([...trie.trie])
我有以下尝试在地图中设置值的代码:
class Trie {
constructor () {
this.trie = new Map()
}
insert(word) {
let current = this.trie
for (let alpha of word) {
if (!current.has(alpha)) current.set(alpha, [])
current = current.get(alpha)
}
current.word = word
}
}
let trie = new Trie()
trie.insert('test')
console.log(trie.trie)
当我尝试 运行 它时,出现错误 .has is not a function
。我在这里错过了什么?
您正在将 current
重新分配给循环内的非 Map 值,因此在后续迭代中,current.has
将不起作用。听起来您需要将 []
改为 new Map
。
class Trie {
constructor () {
this.trie = new Map()
}
insert(word) {
let current = this.trie
for (let alpha of word) {
if (!current.has(alpha)) current.set(alpha, new Map())
current = current.get(alpha)
}
current.word = word
}
}
let trie = new Trie()
trie.insert('test')
console.log([...trie.trie])