Mdd*_*Mdd 1 javascript recursion
我有一个数据树,我正在尝试创建一个递归函数来将树中的每个路径添加为一个字符串数组,以更好地理解递归。我不确定为什么我的方法没有产生期望
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);Run Code Online (Sandbox Code Playgroud)
我要创建的输出是:
[
["home"],
["home", "cars"],
["home", "cars", "ford"],
["home", "cars", "ford", "mustang"],
["home", "cars", "ford", "explorer"],
["home", "food"],
["home", "food", "pizza"]
]
Run Code Online (Sandbox Code Playgroud)
您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, []);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1648 次 |
| 最近记录: |