es6 树形结构找到节点
时间: 2023-07-26 22:12:18 浏览: 44
若要在 ES6 的树形结构中找到一个节点,可以使用递归来实现:
```javascript
function findNode(tree, nodeId) {
if (tree.id === nodeId) {
// 找到节点,返回它
return tree;
} else if (tree.children) {
// 如果当前节点有子节点,遍历子节点
for (let i = 0; i < tree.children.length; i++) {
const result = findNode(tree.children[i], nodeId);
if (result) {
// 找到节点,返回它
return result;
}
}
}
// 没有找到节点,返回 null
return null;
}
// 示例树形结构
const tree = {
id: 1,
children: [
{
id: 2,
children: [
{ id: 4 },
{ id: 5 }
]
},
{
id: 3,
children: [
{ id: 6 },
{ id: 7 }
]
}
]
};
// 找到 id 为 5 的节点
const node = findNode(tree, 5);
console.log(node); // 输出 { id: 5 }
```
在上面的代码中,`findNode` 函数接受两个参数:树形结构和要查找的节点的 ID。如果当前节点的 ID 等于要查找的 ID,就返回当前节点;否则,如果当前节点有子节点,就递归遍历每个子节点,直到找到节点或遍历完所有子节点。如果遍历完所有子节点还没有找到节点,就返回 `null`。