【问题标题】:How to fix 'node is undefined' error when a default value is being passed?传递默认值时如何修复“节点未定义”错误?
【发布时间】:2019-07-17 04:16:42
【问题描述】:

我正在尝试在 javascript 中实现 Trie 数据结构。在仅打印包含 trie 中所有单词的数组的 print 函数中,我有另一个函数 search,它搜索 trie 中的所有单词并将它们推送到数组中。 search 函数有两个参数“node”和“str”,它们都有默认值。当我在不传递任何参数的情况下调用该函数时,尽管节点具有默认值且未定义,但仍会发生错误。

this.print = function(){
        let words = new Array();
        let search = function(node = this.root, string = new String()){
            if(node.keys.size != 0){
                if(node.isEnd() === true){
                    words.push(string);
                }
                for (let letter of node.keys.keys()){
                    search(node.keys.get(letter), string.concat(letter));
                };
            }else{
                (string.length > 0) ? words.push(string) : undefined;
                return;
            }
        };
        search();
        return words.length > 0 ? words : null;
    };

TypeError: 节点未定义 trie.js:44:16

search http://127.0.0.1:5500/trie.js:44
print http://127.0.0.1:5500/trie.js:56
<anonymous> http://127.0.0.1:5500/trie.js:

【问题讨论】:

  • this.root 好像是未定义的
  • 我已经在this.print函数之外定义了this.root

标签: javascript node.js npm trie


【解决方案1】:

试试这个:

this.print = function(self=this){
    let words = new Array();
    let search = function(node = self.root, string = new String()){
        if(node.keys.size != 0){
            if(node.isEnd() === true){
                words.push(string);
            }
            for (let letter of node.keys.keys()){
                search(node.keys.get(letter), string.concat(letter));
            };
        }else{
            (string.length > 0) ? words.push(string) : undefined;
            return;
        }
    };
    search();
    return words.length > 0 ? words : null;
};

【讨论】:

  • 更改是在函数内部将 this 别名为 self 以防止混淆哪个 'this' 被引用。
  • 不客气。如果它解决了您的问题,请接受答案,以便其他人也可以受益。
猜你喜欢
  • 2023-02-23
  • 1970-01-01
  • 2019-12-14
  • 2016-02-05
  • 1970-01-01
  • 1970-01-01
  • 2020-07-24
  • 2015-04-24
  • 1970-01-01
相关资源
最近更新 更多