![](/img/trans.png)
[英]How to fix Flow error when accessing a field with default value on an object?
[英]How to fix 'node is undefined' error when a default value is being passed?
我正在嘗試在javascript中實現Trie數據結構。 在僅打印包含trie中所有單詞的數組的print函數內部,我還有另一個函數搜索,該函數搜索trie中的所有單詞並將其推入數組。 搜索功能兩個參數'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.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;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.