为何Tree.prototype.traversalBF函数未被调用?文件树代码排查
问题分析与解决方案
嘿,我帮你定位到问题的根源了,主要有两个关键错误导致你的traversalBF函数没运行,还有逻辑上的漏洞:
1. 箭头函数未执行,导致traversalBF从未被调用
在你的add方法的else分支里,你写了:
var newNode = () => this.traversalBF(currentNode, pathSplit[n]);
这只是定义了一个箭头函数,但没有实际调用它!所以traversalBF函数根本没被执行,内部的console.log自然不会输出。
你需要直接调用函数并把返回值赋值给newNode,去掉箭头函数的包裹:
var newNode = this.traversalBF(currentNode, pathSplit[n]);
2. traversalBF函数内的条件判断与逻辑漏洞
错误1:赋值运算符代替比较运算符
你写的else if( i = length)是赋值操作(把length的值赋给i),不是比较判断,应该用严格相等运算符===。
错误2:逻辑分支永远不会触发
因为while循环的条件是i < length,循环结束时i的值才等于length,所以循环内部的这个else if分支永远不会被触发。你应该把“未找到匹配项时添加节点”的逻辑移到while循环外面。
错误3:节点匹配逻辑错误
原代码里node.children[i] == pathPart是把节点对象和字符串比较,永远不会相等——你应该比较节点的data属性(假设你的Node类用data存储路径片段)。
修正后的traversalBF函数:
Tree.prototype.traversalBF = function(node, pathPart) { console.log('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'); var length = node.children.length; var i = 0; var found = false; console.log(node); // 循环查找匹配的子节点 while (!found && i < length) { if (node.children[i].data === pathPart) { found = true; return node.children[i]; } i++; } // 循环结束后如果没找到,就创建新节点并添加 if (!found) { var nodeFile = new Node(pathPart); node.children.push(nodeFile); nodeFile.parent = node; return nodeFile; // 记得返回新节点,保证递归能继续 } };
修正后的完整add方法
Tree.prototype.add = function(path){ var pathSplit = path.split('/'); var pathLength = pathSplit.length; console.log(pathLength); let compare = (currentNode, n) => { if(n === pathLength -1){ console.log(pathLength+ " seconds"); console.log(currentNode.data) var nodeFile = new Node(pathSplit[n]); currentNode.children.push(nodeFile); nodeFile.parent = currentNode; } else { var newNode = this.traversalBF(currentNode, pathSplit[n]); // 直接调用函数 console.log(newNode); compare(newNode, n+1); } }; compare(this._root, 0); };
总结
- 确保函数被实际调用,而不是只定义函数引用
- 严格区分赋值运算符
=和比较运算符=== - 调整逻辑分支的位置,确保代码能被执行到
- 正确比较节点的属性,而非节点对象本身
内容的提问来源于stack exchange,提问作者help please
相关产品推荐
相关产品推荐

