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

如何在TypeScript中编写递归函数获取树形结构的顶层父节点

错误原因

递归的else分支缺少return语句,你仅执行了递归调用this.getTopParentNode(rowNode.parent),但没有将该调用的返回值向外传递。当rowNode.parent不为空时,函数执行完else分支后没有显式返回值,默认就会返回undefined,只有最内层命中终止条件的返回值没有被上层接收,最终调用拿到的结果必然是undefined。

修复方案

给else分支的递归调用加上return即可:

private getTopParentNode(rowNode): any {
    if (rowNode.parent == null) {
        return rowNode;
    } else {
        return this.getTopParentNode(rowNode.parent);
    }
}

可选优化建议

  • 可增加入参非空判断,避免rowNode本身为null时调用rowNode.parent抛出异常
  • TypeScript场景下可给rowNode和返回值定义明确类型,替换any提升类型安全

内容的提问来源于stack exchange,提问作者Marox

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 08:24:08