You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修复JavaScript递归搜索函数:始终返回根节点问题

修复树形节点递归search函数的错误

问题根源

你的search函数存在两个关键错误:

  1. 递归调用子节点的search方法后,错误地返回了当前遍历的子节点(instance.children[c]),而非递归调用得到的实际匹配节点——这会导致只要子节点的后代存在匹配项,就返回该子节点而非真正的匹配节点,最终表现为始终返回根节点或上层节点。
  2. 冗余的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 12:15:35