递归调用多个嵌套对象会产生未定义的

时间:2019-05-06 10:20:06

标签: javascript

我写了一个简单的算法,其工作是在专业是教师的情况下找到相应的名称。

给定的代码递归调用函数,直到获得给定的结果。

执行代码时,我得到的最终输出是undefined。正如我期望的那样,这个名字叫ishan。

有人可以帮助我从算法上诊断问题吗?

   
    //Accessing infitely nested Array
    // Infinitely nested Array

    const infiniteArray = [
      {
        name: "Jack",
        age: "98",
        profession: "doctor",
        children: [
          {
            name: "Varun",
            age: "80",
            profession: "scientist",
            children: [
              {
                name: "Ishan",
                age: "62",
                profession: "teacher"
              }
            ]
          }
        ]
      }
    ];
    
    
    
    const accessNestedObject = (infiniteArray) => {
      return infiniteArray.forEach(element => {
        if (element['profession'] === 'teacher') {
          console.log(element.name)
          return element.name
        } else {
          console.log(element["children"])
          return accessNestedObject(element["children"])
        }
      });
    }
    
    const result = accessNestedObject(infiniteArray)
    console.log(result)

1 个答案:

答案 0 :(得分:1)

您得到undefined,因为这是Array#forEach的预期返回值。

您必须声明一个变量,该变量将存储循环的最终结果。

//Accessing infitely nested Array
// Infinitely nested Array

const infiniteArray = [
  {
    name: "Jack",
    age: "98",
    profession: "doctor",
    children: [
      {
        name: "Varun",
        age: "80",
        profession: "scientist",
        children: [
          {
            name: "Ishan",
            age: "62",
            profession: "teacher"
          }
        ]
      }
    ]
  }
];



const accessNestedObject = (infiniteArray) => {
  let result = null;

  infiniteArray.forEach(element => {
    if (element.profession === 'teacher') {
      result = element.name;
    } else {
      result = accessNestedObject(element.children);
    }
  });
  
  return result;
}

const result = accessNestedObject(infiniteArray);
console.log(result);