gpt4 book ai didi

javascript - 循环到我的对象中的文件系统结构以获取所有文件

转载 作者:行者123 更新时间:2023-11-28 17:50:45 25 4
gpt4 key购买 nike

我从我的服务器获取一个 Javascript 对象,它描述了一个文件系统。现在我想获取系统中所有文件的路径,例如树的端点。

文件结构示例:

└── pages
└── services
└── project
│── headline
│── test
   │   └── text
│ └── picture
│── text

可读的 JSON:

{
"path":"/pages/services/project",
"is_dir":true,
"children":[
{
"path":"/pages/services/project/headline",
"is_dir":false,
"children":[

]
},
{
"path":"/pages/services/project/text",
"is_dir":false,
"children":[

]
},
{
"path":"/pages/services/project/test/",
"is_dir":true,
"children":[
{
"path":"/pages/services/project/test/text",
"is_dir":false,
"children":[

]
},
{
"path":"/pages/services/project/test/picture",
"is_dir":false,
"children":[

]
}
]
}

] }

预期输出:

/pages/services/project/headline
/pages/services/project/text
/pages/services/project/test/text
/pages/services/project/test/picture

我玩了一下递归,并制作了一个愚蠢的函数,当目录只有一个子目录时该函数可以工作。我的问题是我无法掌握照顾更多 child 的方法。有没有办法迭代每个 child ?

这是我的代码:

var json = {"path":"/pages/services/project", "is_dir":true, "children":[{"path":"/pages/services/project/headline","is_dir":false,"children":[]},{"path":"/pages/services/project/text","is_dir":false,"children":[]},
{"path":"/pages/services/project/test/","is_dir":true,"children":[{"path":"/pages/services/project/test/text","is_dir":false,"children":[]},
{"path":"/pages/services/project/test/picture","is_dir":false,"children":[]}]}]};

json.children.forEach(function (child) {
out(goToDeepestPoint(child).path);
});



function goToDeepestPoint(node) {
if (node.is_dir)
return goToDeepestPoint(node.children[0]);
else
return node;
}

function out()
{
var args = Array.prototype.slice.call(arguments, 0);
document.getElementById('output').innerHTML += args.join(" ") + "\n";
}
<pre id="output"></pre>

最佳答案

工作解决方案:

var json = {"path":"/pages/services/project", "is_dir":true, "children":[{"path":"/pages/services/project/headline","is_dir":false,"children":[]},{"path":"/pages/services/project/text","is_dir":false,"children":[]},
{"path":"/pages/services/project/test/","is_dir":true,"children":[{"path":"/pages/services/project/test/text","is_dir":false,"children":[]},
{"path":"/pages/services/project/test/picture","is_dir":false,"children":[]}]}]};

json.children.forEach(function (child) {
goToDeepestPoint(child);
});



function goToDeepestPoint(node) {
if (node.is_dir){
for(var i=0;i<node.children.length;i++){
goToDeepestPoint(node.children[i]);
}
}
else {
out(node.path);
}
}

function out()
{
var args = Array.prototype.slice.call(arguments, 0);
document.getElementById('output').innerHTML += args.join(" ") + "\n";
}

关于javascript - 循环到我的对象中的文件系统结构以获取所有文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45565900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com