gpt4 book ai didi

javascript - 递归遍历树以创建面包屑列表

转载 作者:行者123 更新时间:2023-11-28 13:20:33 25 4
gpt4 key购买 nike

我有一棵数据树,并尝试创建一个递归函数,将树中的每个路径添加为字符串数组,以更好地理解递归。我不确定为什么我的方法没有产生期望

var tree = {
"name": "home",
"children": [
{
"name": "cars",
"children": [
{
"name": "ford",
"children": [
{
"name": "mustang"
},
{
"name": "explorer"
}
]
}
]
},
{
"name": "food",
"children": [
{
"name": "pizza"
}
]
}
]
};

var list = [];
var path = [];

function traverse(node) {
if (node.name) {
path.push(node.name)
}

if (!node.children) {
if (path.length) {
list.push(path);
}
return;
} else {
node.children.forEach(function(item) {
traverse(item);
});
}
}

traverse(tree);
console.log(list);

我想要创建的输出是:

[
["home"],
["home", "cars"],
["home", "cars", "ford"],
["home", "cars", "ford", "mustang"],
["home", "cars", "ford", "explorer"],
["home", "food"],
["home", "food", "pizza"]
]

最佳答案

您在所有迭代中修改相同的path 数组。您应该复制它:

var list = [];
function traverse(node, path) {
if ( !path )
path = [];
if (node.name) {
path.push(node.name)
}
list.push(path);
if (node.children) {
node.children.forEach(function(item) {
traverse(item, path.slice());
});
}
}
traverse(tree, []);

关于javascript - 递归遍历树以创建面包屑列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33550931/

25 4 0
文章推荐: css - IIS - 浏览文件时拒绝访问
文章推荐: HTTP 请求适用于 Postman 但不适用于 Swift
文章推荐: javascript - 将
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com