【问题标题】:How do I fix the error '.has is not a function' when using JavaScript Map?使用 JavaScript Map 时如何修复错误“.has 不是函数”?
【发布时间】:2021-12-01 11:59:07
【问题描述】:

我有以下代码尝试在 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。我在这里错过了什么?

【问题讨论】:

    标签: javascript oop ecmascript-6 hashmap es6-class


    【解决方案1】:

    您将 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])

    【讨论】:

    • 非常感谢,我不敢相信我错过了
    猜你喜欢
    • 2019-07-10
    • 2021-03-29
    • 1970-01-01
    • 2019-12-25
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    • 2021-06-12
    • 2019-07-01
    相关资源
    最近更新 更多