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

递归函数未迭代到循环中下一个元素的问题及修复方法

问题修复:递归查找Item时数组第二个元素无法访问

问题原因

你的递归函数存在逻辑错误:在遍历items数组时,只要当前元素的id不匹配,就立即返回递归查找其子项的结果,这直接终止了循环,导致数组中第一个元素之后的所有项都没有机会被检查。

修复方案

修改逻辑:先递归查找当前元素的子项,如果子项中找到了目标,就返回结果;如果没找到,不要立即返回,而是继续循环遍历下一个元素。只有当所有元素及其子项都检查完仍未找到时,才返回undefined。

修复后的代码:

class Item {
  items: Item[] = [];
  constructor(public id: string) {}
}

function getItembyIdRecursively(id: string, items: Item[]): Item | undefined {
  for (const item of items) {
    if (item.id === id) {
      return item;
    }
    // 先递归查找子项,找到则返回,没找到继续循环下一个元素
    const foundChild = getItembyIdRecursively(id, item.items);
    if (foundChild) {
      return foundChild;
    }
  }
  return undefined;
}

const item1 = new Item("1");
const item2 = new Item("2");
item1.items.push(new Item("1.2"));
const items = [item1, item2];

const foundItem = getItembyIdRecursively("2", items);

console.log(foundItem?.id); // 现在会输出"2"

说明

  • 移除了原代码中的else分支,避免循环提前终止
  • 递归查找子项后,仅当找到结果时才返回,否则继续遍历数组的下一个元素
  • 最后访问foundItem.id时添加了可选链操作符?.,避免未找到时出现空指针错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 13:43:20