简体   繁体   中英

How to fix 'node is undefined' error when a default value is being passed?

I am trying to implement Trie data structure in javascript. Inside the print function which just prints an array containing all the word in the trie, I have another function search, which searches for all words in the trie and pushes them to the array. search function two parameters 'node' and 'str' which both have default values. When I invoke the function without passing any argument the error occurs although the node has a default value and is not undefined.

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: node is undefined 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:

Try this:

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;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM