gpt4 book ai didi

javascript - 递归调用多个嵌套对象给出未定义

转载 作者:行者123 更新时间:2023-11-30 19:35:19 27 4
gpt4 key购买 nike

我写了一个简单的算法,它的工作是找到职业是教师的对应名称。

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

在执行代码时,我得到的最终输出是 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)

最佳答案

您将得到 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);

关于javascript - 递归调用多个嵌套对象给出未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56003197/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com