You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用JavaScript Map时出现'.has is not a function'错误该如何解决?

错误原因

你的代码触发报错的核心原因是子节点类型错误:

  • 初始current变量指向根Map实例,可以正常调用has、set、get方法
  • 第一次匹配不到字符时,你给字符对应的值设置为普通数组[],current被重新赋值为数组后,数组原型链上没有Map的相关方法,遍历到第二个字符时调用current.has()就会抛出异常。

修复方案

字典树的每个子节点都需要是Map类型才能支持后续的字符查询操作,只需要把初始化子节点时的数组改为新的Map实例即可。

修复后完整代码

class Trie {
  constructor () {
    this.trie = new Map()
  }

  insert(word) {
    let current = this.trie
    for (let alpha of word) {
      // 子节点统一用Map类型存储
      if (!current.has(alpha)) current.set(alpha, new Map())
      current = current.get(alpha)
    }
    // 标记当前节点为单词结束节点
    current.isEnd = true
    current.word = word
  }
}

let trie = new Trie()
trie.insert('test')
console.log(trie.trie)

内容的提问来源于stack exchange,提问作者Caleb Oki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 03:36:04