我創建了遞回函式來列出所有檔案和檔案夾,我列出得很好,但我需要路徑名以及如何附加請幫助我。
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
uj5u.com熱心網友回復:
您可以添加一個可選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)
uj5u.com熱心網友回復:
要將節點名稱附加到先前的結果,您必須以某種方式傳遞嵌套結構。一種方法是通過函式引數。在下面的解決方案中,我將當前路徑作為陣列傳遞。
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));
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/395620.html
標籤:javascript 数组 嵌套循环
上一篇:多項式的確定
下一篇:外鍵int陣列C#
