无论是否有足够的 return 语句,递归函数都返回 undefined

J D*_*Doe 3 javascript recursion

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

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");
Run Code Online (Sandbox Code Playgroud)

Cer*_*nce 5

forEach返回undefined,所以

return node.forEach(el => {
  return recurseFind(el, id);
});
Run Code Online (Sandbox Code Playgroud)

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

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

return node.forEach(el => {
  return recurseFind(el, id);
});
Run Code Online (Sandbox Code Playgroud)