我有一个数据树,我试图创建一个递归函数来将每个路径添加到树中作为一个字符串数组,以便更好地理解递归。我不知道为什么我的方法不产生预期通过树递归创建面包屑列表
var tree = {
\t "name": "home",
\t "children": [
\t \t {
\t \t \t "name": "cars",
\t \t \t "children": [
\t \t \t \t {
\t \t \t \t \t "name": "ford",
\t \t \t \t \t "children": [
\t \t \t \t \t \t {
\t \t \t \t \t \t \t "name": "mustang"
\t \t \t \t \t \t },
\t \t \t \t \t \t {
\t \t \t \t \t \t \t "name": "explorer"
\t \t \t \t \t \t }
\t \t \t \t \t ]
\t \t \t \t }
\t \t \t ]
\t \t },
\t \t {
\t \t \t "name": "food",
\t \t \t "children": [
\t \t \t \t {
\t \t \t \t \t "name": "pizza"
\t \t \t \t }
\t \t \t ]
\t \t }
\t ]
};
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"]
]
好一件事你正在存储递归函数外的路径变量,并且永远不会重置其值。 – thatidiotguy