js实现层级
实现层级结构的 JavaScript 方法
在 JavaScript 中,层级结构通常通过对象嵌套或数组嵌套的方式实现。以下是几种常见的实现方法:
使用对象嵌套 对象可以自然地表示层级关系,通过属性嵌套属性来构建树形结构。
const hierarchy = {
name: 'Root',
children: [
{
name: 'Child 1',
children: [
{ name: 'Grandchild 1', children: [] },
{ name: 'Grandchild 2', children: [] }
]
},
{
name: 'Child 2',
children: []
}
]
};
使用类表示节点 定义一个节点类,每个实例代表层级中的一个节点。
class TreeNode {
constructor(value) {
this.value = value;
this.children = [];
}
addChild(childNode) {
this.children.push(childNode);
}
}
const root = new TreeNode('Root');
const child1 = new TreeNode('Child 1');
const child2 = new TreeNode('Child 2');
root.addChild(child1);
root.addChild(child2);
使用扁平数组和引用 当数据存储在扁平数组中时,可以通过引用构建层级。
const flatData = [
{ id: 1, parentId: null, name: 'Root' },
{ id: 2, parentId: 1, name: 'Child 1' },
{ id: 3, parentId: 1, name: 'Child 2' },
{ id: 4, parentId: 2, name: 'Grandchild 1' }
];
function buildTree(items) {
const map = {};
const tree = [];
items.forEach(item => {
map[item.id] = { ...item, children: [] };
});
items.forEach(item => {
if (item.parentId === null) {
tree.push(map[item.id]);
} else {
map[item.parentId].children.push(map[item.id]);
}
});
return tree;
}
const hierarchicalData = buildTree(flatData);
遍历层级结构的方法
深度优先遍历(DFS) 递归地访问每个节点的子节点。
function dfs(node) {
console.log(node.value);
node.children.forEach(child => dfs(child));
}
广度优先遍历(BFS) 使用队列按层级访问节点。
function bfs(root) {
const queue = [root];
while (queue.length > 0) {
const node = queue.shift();
console.log(node.value);
node.children.forEach(child => queue.push(child));
}
}
实用技巧
查找特定节点 通过遍历查找满足条件的节点。
function findNode(root, predicate) {
if (predicate(root)) return root;
for (const child of root.children) {
const found = findNode(child, predicate);
if (found) return found;
}
return null;
}
计算深度 递归计算树的深度。

function getDepth(node) {
if (node.children.length === 0) return 1;
return 1 + Math.max(...node.children.map(getDepth));
}
这些方法可以根据具体需求进行调整和组合,适用于菜单系统、组织结构图、文件目录等各种需要层级结构的场景。






