修复JavaScript递归搜索函数:始终返回根节点问题
修复树形节点递归search函数的错误
问题根源
你的search函数存在两个关键错误:
- 递归调用子节点的
search方法后,错误地返回了当前遍历的子节点(instance.children[c]),而非递归调用得到的实际匹配节点——这会导致只要子节点的后代存在匹配项,就返回该子节点而非真正的匹配节点,最终表现为始终返回根节点或上层节点。 - 冗余的
instance变量完全可以用this替代,因为实例方法内部的this天然指向当前节点实例。
修复后的代码
var node = function(url) { this.url = url; this.parent = null; this.children = []; this.search = function(targetUrl) { // 检查当前节点是否匹配目标URL if (targetUrl === this.url) { return this; } // 遍历所有子节点递归搜索 for (var c = 0; c < this.children.length; c++) { const foundNode = this.children[c].search(targetUrl); // 找到匹配节点则直接返回 if (foundNode !== null) { return foundNode; } } // 未找到任何匹配节点 return null; } }
修复说明
- 修正递归返回逻辑:将递归调用的结果存入变量
foundNode,确认存在匹配时返回该结果,而非当前子节点,确保返回的是真正匹配的深层节点。 - 简化代码结构:移除不必要的
instance变量,直接用this访问当前实例的属性和方法,提升代码可读性。 - 参数命名优化:将参数名改为
targetUrl,避免与实例的url属性混淆,逻辑更清晰。
测试验证
// 构建测试树形结构 const root = new node('/'); const page1 = new node('/page1'); const page2 = new node('/page2'); const subpage = new node('/page2/subpage'); root.children.push(page1); root.children.push(page2); page2.children.push(subpage); // 验证搜索结果 console.log(root.search('/page2/subpage') === subpage); // true console.log(root.search('/page1') === page1); // true console.log(root.search('/') === root); // true console.log(root.search('/not-exist')); // null
内容的提问来源于stack exchange,提问作者user1655229
相关产品推荐
相关产品推荐

