当前位置:首页 > JavaScript

js实现树状

2026-02-01 18:37:43JavaScript

实现树状结构的核心方法

递归遍历构建树 递归是处理树状结构的核心方法,通过递归可以方便地遍历和构建树。以下是一个简单的递归构建树的示例:

function buildTree(data, parentId = null) {
  const tree = [];
  for (const item of data) {
    if (item.parentId === parentId) {
      const children = buildTree(data, item.id);
      if (children.length > 0) {
        item.children = children;
      }
      tree.push(item);
    }
  }
  return tree;
}

扁平数组转树结构 当数据以扁平数组形式存储时,需要将其转换为树状结构。这种方法通常使用对象来存储节点引用:

function arrayToTree(items) {
  const map = {};
  const roots = [];

  items.forEach(item => {
    map[item.id] = { ...item, children: [] };
  });

  items.forEach(item => {
    if (item.parentId && map[item.parentId]) {
      map[item.parentId].children.push(map[item.id]);
    } else {
      roots.push(map[item.id]);
    }
  });

  return roots;
}

树结构的渲染方法

递归渲染组件 在React中可以使用递归组件来渲染树状结构:

js实现树状

function TreeNode({ node }) {
  return (
    <div>
      <div>{node.name}</div>
      {node.children && (
        <div style={{ marginLeft: '20px' }}>
          {node.children.map(child => (
            <TreeNode key={child.id} node={child} />
          ))}
        </div>
      )}
    </div>
  );
}

使用第三方库 对于复杂的树状结构,可以使用专门的库如:

  • react-treebeard:提供丰富的树状UI组件
  • rc-tree:Ant Design使用的树组件基础
  • d3-hierarchy:强大的数据可视化树结构库

树结构的常见操作

查找节点 通过深度优先或广度优先搜索查找特定节点:

js实现树状

function findNode(tree, id) {
  for (const node of tree) {
    if (node.id === id) return node;
    if (node.children) {
      const found = findNode(node.children, id);
      if (found) return found;
    }
  }
  return null;
}

遍历树结构 实现树的多种遍历方式:

// 深度优先遍历
function traverseDFS(tree, callback) {
  tree.forEach(node => {
    callback(node);
    if (node.children) traverseDFS(node.children, callback);
  });
}

// 广度优先遍历
function traverseBFS(tree, callback) {
  const queue = [...tree];
  while (queue.length) {
    const node = queue.shift();
    callback(node);
    if (node.children) queue.push(...node.children);
  }
}

性能优化技巧

虚拟滚动 对于大型树结构,实现虚拟滚动避免渲染所有节点:

import { FixedSizeList as List } from 'react-window';

function TreeList({ treeData }) {
  const flatData = flattenTree(treeData);

  return (
    <List
      height={600}
      itemCount={flatData.length}
      itemSize={35}
      width={300}
    >
      {({ index, style }) => (
        <div style={{ ...style, paddingLeft: `${flatData[index].depth * 20}px` }}>
          {flatData[index].name}
        </div>
      )}
    </List>
  );
}

懒加载 实现按需加载子树节点:

async function loadChildren(node) {
  if (!node.children && !node.hasLoaded) {
    const children = await fetchChildren(node.id);
    node.children = children;
    node.hasLoaded = true;
  }
}

标签: 树状js
分享给朋友:

相关文章

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 实现页面跳转,这是最常用的方法。 window.location.href = 'https:/…

js实现图片轮播

js实现图片轮播

实现基础图片轮播 使用HTML、CSS和JavaScript创建一个简单的图片轮播。HTML部分定义轮播容器和图片,CSS设置样式和动画效果,JavaScript处理轮播逻辑。 <div c…

js实现乘

js实现乘

JavaScript 实现乘法运算 在 JavaScript 中实现乘法运算可以通过多种方式完成,包括基本运算符、函数封装以及高级算法(如大数乘法)。以下是几种常见方法: 使用基本乘法运算符 Jav…

js实现延迟

js实现延迟

实现延迟的方法 在JavaScript中,实现延迟操作有多种方式,以下是几种常见的方法: 使用setTimeout函数 setTimeout是JavaScript中最常用的延迟执行方法。它接受一个回…

js实现tab选项卡切换

js实现tab选项卡切换

实现Tab选项卡切换的JavaScript方法 使用纯JavaScript实现Tab切换功能,可以通过监听点击事件动态切换内容显示状态。以下是两种常见实现方式: 基础DOM操作实现 /…

js实现点击显示和隐藏

js实现点击显示和隐藏

实现点击显示和隐藏的JavaScript方法 使用classList.toggle切换类名 通过添加/移除CSS类控制元素的显示与隐藏,需提前在CSS中定义隐藏样式(如display: none)。…