我有一个递归函数,它打印深嵌套对象中的每个子对象。
const tree = {
name: "Anand",
children: [
{
name: "Dashrath",
children: [
{
name: "Sitesh",
children: [
{
name: "Yadnesh",
children: []
}
]
}
]
},
{
name: "Machindra",
children: [
{
name: "Tejas",
children: [
{
name: "Tanishka",
children: []
}
],
},
{
name: "Amol",
children: [],
},
{
name: "Amit",
children: []
}
]
}
]
}
function printTree(t) {
if (t.children.length === 0) {
return
}
t.children.forEach((child,index) => {
console.log(child.name);
printTree(child);
})
}
printTree(tree);
输出:dashrath, sitesh, yadnesh, machindra, tanishka, amol, amit
我想要这样的东西第一代dashrath,第二代sitesh,第三代yadnesh,第一代machindra,第二代tejas,第三代tanishka,第二代amol,第三代amit
您可以让printTree
函数接受depth
参数并在每次递归调用时适当地增加它,如下所示:
function printTree(t, depth = 0) {
if (t.children.length === 0) {
return
}
t.children.forEach((child,index) => {
// you'd need to do some extra formatting here if you
// want ordinals like "1st", "2nd", etc.
console.log(`gen ${depth + 1}: ${child.name}`);
printTree(child, depth + 1);
})
}
printTree(tree);