javascript - 嵌套树的递归函数不按“顺序”返回
问题描述
我有一个包含嵌套数组的数据结构 - 我想显示数据以使其看起来像一个文件结构 - 所以嵌套数据表示为嵌套文件/文件夹。然而,在控制台记录递归函数返回的内容并不代表数据结构的嵌套性质。
这是我的数据结构:
const data = {
"root": [
{
"type": "folder",
"name": "one",
"children": [
{
"type": "folder",
"name": "one",
"children": []
},
{
"type": "file",
"name": "two",
"extension": ".txt",
"preview": "photos.google.com/abc.jpg"
},
{
"type": "file",
"name": "four",
"extension": ".txt",
"preview": "photos.google.com/abc.jpg"
}
]
},
{
"type": "file",
"name": "two",
"extension": ".txt",
"preview": "photos.google.com/abc.jpg"
},
{
"type": "file",
"name": "three",
"extension": ".txt",
"preview": "photos.google.com/abc.jpg"
},
{
"type": "file",
"name": "four",
"extension": ".txt",
"preview": "photos.google.com/abc.jpg"
}
]
}
我的递归函数:
const recurse = (data, children = false) => {
data.forEach(object => {
if (object.type === 'folder') {
recurse(object.children, true)
}
if (children) {
console.log(' ' + object.type + ' ' + object.name);
} else {
console.log(object.type + ' ' + object.name);
}
})
}
recurse(data.root)
和控制台日志:
' folder one'
' file two'
' file four'
'folder one'
'file two'
'file three'
'file four'
所以功能是从结构的内部打印出来。如果我想以反映数据结构嵌套性质的方式显示它,我应该使用什么方法?提前致谢
解决方案
@j.xavier.atero 比我快一点。:)
我认为您必须将递归放在函数的末尾。这样你就得到了folder one
第一个,然后是它的孩子。
const recurse = (data, children = false) => {
data.forEach(object => {
if (children) {
console.log(' ' + object.type + ' ' + object.name);
} else {
console.log(object.type + ' ' + object.name);
}
if (object.type === 'folder') {
recurse(object.children, true)
}
})
}
recurse(data.root)
更新评论
我想说为递归函数添加一个额外的参数。
const recurse = (data, level = 0) => {
data.forEach(object => {
console.log(Array(level).join(' ') + object.type + ' ' + object.name);
if (object.type === 'folder') {
recurse(object.children, level + 1)
}
})
}
recurse(data.root)
这会跟踪递归函数的深度。你甚至不需要检查它是否是孩子了。
推荐阅读
- bash - 覆盖行的脚本的着色输出?
- html - “链接标签和href之间的关系” - 这是什么意思?
- reactjs - 仅在另一个异步功能完成后如何强制执行功能
- swift - 无法快速获取 downloadURL 火存储的值
- python-3.x - 打印语音频道中的成员列表
- prometheus - Prometheus 几乎没有使用过 Grafana 中未显示的计数器
- javascript - 使图像可拖动的问题
- typescript - 重叠类型的类型定义
- laravel - 如何将get var传递给后端?
- phaser-framework - 无法看到使用 Phaser 3.24.1 加载的图像