如何在递归函数javascript中得到path_name?
How to get path_name in recursive funciton javascript?
我创建了用于列出所有文件和文件夹的递归函数,我列出得很好,但我需要路径名以及如何附加请帮助我。
const treeData = [
{
name: "root",
children: [
{ name: "src", children: [{ name: "index.html" }] },
{ name: "public", children: [] },
],
},
];
const RecursiveTree = (data) => {
data.map((item) => {
console.log(item.name);
if (item.children) {
RecursiveTree(item.children);
}
});
};
RecursiveTree(treeData);
如何获取路径名
预期结果
root
root/src
root/src/index.html
您可以添加一个可选的 path=''
参数,开始为空,然后将当前路径传递给自身:
const treeData = [{
name: 'root',
children : [{
name: 'src',
children: [{
name: 'index.html'
}]
}, {
name: 'public',
children: []
}]
}];
const RecursiveTree = (data, path='') => {
data.forEach((item) => {
const currentPath = path + "/" + item.name
console.log(currentPath )
if (item.children) {
RecursiveTree(item.children, currentPath)
}
})
}
RecursiveTree(treeData)
要将节点名称附加到先前的结果,您必须以某种方式传递嵌套结构。一种方法是通过函数参数。在下面的解决方案中,我会将当前路径作为数组传递。
const treeData = [
{
name: "root",
children: [
{ name: "src", children: [{ name: "index.html" }] },
{ name: "public", children: [] },
],
},
];
function recursiveTree(tree, currentPath = [], paths = []) {
if (!tree) return;
for (const node of tree) {
const nodePath = currentPath.concat(node.name);
paths.push(nodePath.join("/"));
recursiveTree(node.children, nodePath, paths);
}
return paths;
}
console.log(recursiveTree(treeData));
我创建了用于列出所有文件和文件夹的递归函数,我列出得很好,但我需要路径名以及如何附加请帮助我。
const treeData = [
{
name: "root",
children: [
{ name: "src", children: [{ name: "index.html" }] },
{ name: "public", children: [] },
],
},
];
const RecursiveTree = (data) => {
data.map((item) => {
console.log(item.name);
if (item.children) {
RecursiveTree(item.children);
}
});
};
RecursiveTree(treeData);
如何获取路径名 预期结果
root
root/src
root/src/index.html
您可以添加一个可选的 path=''
参数,开始为空,然后将当前路径传递给自身:
const treeData = [{
name: 'root',
children : [{
name: 'src',
children: [{
name: 'index.html'
}]
}, {
name: 'public',
children: []
}]
}];
const RecursiveTree = (data, path='') => {
data.forEach((item) => {
const currentPath = path + "/" + item.name
console.log(currentPath )
if (item.children) {
RecursiveTree(item.children, currentPath)
}
})
}
RecursiveTree(treeData)
要将节点名称附加到先前的结果,您必须以某种方式传递嵌套结构。一种方法是通过函数参数。在下面的解决方案中,我会将当前路径作为数组传递。
const treeData = [
{
name: "root",
children: [
{ name: "src", children: [{ name: "index.html" }] },
{ name: "public", children: [] },
],
},
];
function recursiveTree(tree, currentPath = [], paths = []) {
if (!tree) return;
for (const node of tree) {
const nodePath = currentPath.concat(node.name);
paths.push(nodePath.join("/"));
recursiveTree(node.children, nodePath, paths);
}
return paths;
}
console.log(recursiveTree(treeData));