【问题标题】:Having a error in Trie implementation (Javascript)Trie 实现中出现错误(Javascript)
【发布时间】:2018-06-03 22:30:39
【问题描述】:

我正在实现 Trie 算法的添加功能,但它给了我以下错误:

未捕获的类型错误:节点不是构造函数

...在此代码行中:

node.children[char_pos]=new Array(string[0], new node());

拜托,你能告诉我发生了什么吗?

感谢您的帮助。

这是我的代码:

var node = function(){

    this.children= new Array(26);
    this.last_char=false;
};

function add(word, node){

    char_pos=word.charCodeAt(0) - 'a'.charCodeAt(0);

    if(word.length==1){

        if(node.children[char_pos]==null){ 

            node.children[char_pos]=word[0];
            node.last_char=true;
            return;

        }else{
            return;
        };

    }else{

        if(node.children[char_pos]==null){ 
            node.children[char_pos]=new Array(word[0], new node());
        };
    };

    word=word.substring(1);
    add(word, node.children[char_pos][1]);
};

【问题讨论】:

  • 请不要为变量使用受保护的名称,例如string
  • 为什么代码周围有**?
  • @Luca 好的。我改变它=)
  • @Geuis 因为我想突出显示给我错误的代码行。

标签: javascript tree trie


【解决方案1】:

你先说

var node // = ...

然后

function add(word, node){

我想你会用一些 instance 节点调用,一个节点,而不是你的节点 构造函数

在您的函数添加中,identifier node 解析为您的参数“node”,具有 same identifier 的构造函数无法从这里。 写node = new node()会不会失去节点功能吧?

标准通过使用第一个大写字母(如 Node)和 Node、node 的实例来为您的构造函数或类命名,从而帮助您解决此问题,这样您就不会覆盖您的标识符。

事实上,您确实应该选择尚未使用的标识符,因为您将覆盖它们,并使后者不可用。

【讨论】:

    猜你喜欢
    • 2020-06-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多