首页 > 解决方案 > 无论返回语句是否足够,递归函数都返回未定义

问题描述

我已经阅读了一些关于它的问题和答案。看起来我的递归函数有足够的“返回”语句,所以......我不知道为什么它返回未定义......我添加了额外的日志语句以表明函数本身找到了元素,但没有返回它...

let animals = [
  {
    name: "dogs",
    id: 1,
    children: [
      {
        name: "lessie",
        id: 2
      },
      {
        name: "bark-a-lot",
        id: 3
      }
    ]
  },
  {
    name: "cats",
    id: 4,
    children: [
      {
        name: "meows-a-lot",
        id: 5,
        children: [
          {
            name: "meows-a-lot-in-the-morning",
            id: 6
          }
        ]
      },
      {
        name: "whisk-ass",
        id: 7
      }
    ]
  }
];

function recurseFind(node, id) {
  if (Array.isArray(node)) {
    return node.forEach(el => {
      return recurseFind(el, id);
    });
  } else {
    if (node.id === id) {
      console.log("node matched", node.id, id, node);
      return node;
    } else if (node.children) {
      return node.children.forEach(child => {
        return recurseFind(child, id);
      });
    } else {
      return "not found";
    }
  }
}

const found = recurseFind(animals, 6);
console.log("found", found, "wtf");

标签: javascriptrecursion

解决方案


forEach返回undefined,所以

return node.forEach(el => {
  return recurseFind(el, id);
});

undefined无论递归调用找到什么,都会返回。

我会改用for循环,如果找到匹配项,则返回它:

let animals = [
  {
    name: "dogs",
    id: 1,
    children: [
      {
        name: "lessie",
        id: 2
      },
      {
        name: "bark-a-lot",
        id: 3
      }
    ]
  },
  {
    name: "cats",
    id: 4,
    children: [
      {
        name: "meows-a-lot",
        id: 5,
        children: [
          {
            name: "meows-a-lot-in-the-morning",
            id: 6
          }
        ]
      },
      {
        name: "whisk-ass",
        id: 7
      }
    ]
  }
];

function recurseFind(node, id) {
  if (Array.isArray(node)) {
    for (const el of node) {
      const result = recurseFind(el, id);
      if (result) return result;
    }
  } else {
    if (node.id === id) {
      return node;
    } else if (node.children) {
      for (const child of node.children) {
        const result = recurseFind(child, id);
        if (result) return result;
      }
    }
  }
}

const found = recurseFind(animals, 6) || 'not found';
console.log("found", found);


推荐阅读