Javascript 如何计算树中子节点的路径?
我有一棵这样的树:Javascript 如何计算树中子节点的路径?,javascript,Javascript,我有一棵这样的树: var tree = [ { type: "folder", children: [ { type: "folder", children: [ { type: "document", id: 1, children: [] } ] } ] }, {
var tree = [
{
type: "folder",
children: [
{
type: "folder",
children: [
{
type: "document",
id: 1,
children: []
}
]
}
]
},
{
type: "folder",
children: []
}
];
getPathToNode(tree, function (node) {
return node.type === "document" && node.id === 1;
})
此树的叶子总是有一个空的子数组
我需要构造一个函数,将索引路径返回到满足给定条件的节点。函数的调用方式如下:
var tree = [
{
type: "folder",
children: [
{
type: "folder",
children: [
{
type: "document",
id: 1,
children: []
}
]
}
]
},
{
type: "folder",
children: []
}
];
getPathToNode(tree, function (node) {
return node.type === "document" && node.id === 1;
})
并将返回以下内容:
[0, 0, 0]
其中描述了该节点的路径:
tree[0].children[0].children[0]
到目前为止,我得到的就是这个递归函数:
function getPathToNode(tree, fn) {
return tree.reduce(function (path, node, i) {
if (fn(node)) {
return path.concat(i);
}
if (node.children.length > 0) {
const pathToNode = getPathToNode(node.children, fn);
return pathToNode.length > 0 ? path.concat(i, pathToNode) : [];
}
return [];
}, []);
}
我认为该函数需要在遍历时构建一条路径,然后,如果它到达一个叶而没有找到节点,则只删除该路径中属于未找到节点的分支的部分,然后继续使用其他分支。由于迭代可能提前退出,该建议使用该路径
然后您可以使用一个变量作为级别和所需的索引
函数getPathToNode(节点,fn){
var路径=[];
返回节点。部分(功能iter(级别){
返回函数(a,i){
path.length=级别;
路径[级别]=i;
返回fn(a)| a.children.some(iter(level+1));
};
}(0)&&path;
}
变量树=[{type:“文件夹”,子项:[{type:“文件夹”,子项:[{type:“文档”,id:1,子项:[]}]},{type:“文件夹”,子项:[]},
结果=getPathToNode(树,函数(节点){
返回node.type==“document”&&node.id==1;
});
控制台日志(结果)代码>您是否尝试过学习/使用递归?我编辑了我的问题,以包括我迄今为止尝试过的内容。是的,这绝对是递归的工作,我通常用它来管理,但这项任务对我来说要困难得多。@silvenon,太多了?不,很少,这就是为什么它令人印象深刻的原因。:)