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

JavaScript中如何设置isParentEmpty递归停止条件 避免循环依赖无限调用

递归终止条件设置方案

你可以通过递归深度计数的方式实现终止逻辑,核心逻辑是:items数组的节点最长依赖链路不可能超过数组本身的长度,一旦递归次数等于数组长度,就说明要么已经遍历完所有节点,要么出现了循环依赖,直接终止递归即可。

具体改动点:

  • 给isParentEmpty方法新增第三个可选参数depth,默认值设置为0
  • 方法入口处新增判断:如果当前depth大于等于items数组的长度,直接返回false终止递归
  • 递归调用this.isParentEmpty前新增parentItem非空判断,避免空值报错,同时传入depth + 1作为新的深度参数

修改后的完整代码:

isParentEmpty(item, items, depth = 0) {
  // 新增终止条件:递归深度等于数组长度,直接终止避免无限循环
  if (depth >= items.length) {
    return false
  }
  const parentSystemRecordId = R.path(['parent', 'id'], item);
  
  if(!parentSystemRecordId || !item.isDependentList) {
    return false;
  }
  
  const parentItem = 
    items.find(({ _id }) => Number(_id) === parentSystemRecordId);
  // 新增parentItem非空判断,递归时传入深度+1
  if(parentItem && this.isParentEmpty(parentItem, items, depth + 1)) {
    return true;
  }
          
  return parentItem && !R.path(['value', 'id'], parentItem);
}

逻辑说明

假设items数组长度为3,所有合法的父级依赖链路最多只有3层(比如A的父级是B,B的父级是C,C没有父级),如果递归到第3次还没有触发原有终止条件,就说明链路出现了循环(比如C的父级又指回了A),此时触发新增的终止条件即可避免无限循环。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 05:09:01