当前位置:首页 > JavaScript

js实现treelog

2026-03-14 04:16:33JavaScript

实现树形日志(TreeLog)的 JavaScript 方法

数据结构设计

使用嵌套对象或数组表示树形结构,每个节点包含日志内容和子节点信息:

const treeLog = {
  message: "Root log",
  timestamp: new Date(),
  children: [
    {
      message: "Child log 1",
      timestamp: new Date(),
      children: []
    }
  ]
};

递归渲染函数

通过递归遍历树形结构生成可视化日志:

function renderTreeLog(node, indent = 0) {
  const indentStr = ' '.repeat(indent * 2);
  console.log(`${indentStr}${node.message} [${node.timestamp.toISOString()}]`);

  node.children.forEach(child => {
    renderTreeLog(child, indent + 1);
  });
}

动态添加日志

提供添加子日志的方法:

js实现treelog

function addChildLog(parentNode, message) {
  const newLog = {
    message,
    timestamp: new Date(),
    children: []
  };
  parentNode.children.push(newLog);
  return newLog;
}

样式增强版本

使用HTML/CSS增强可视化效果:

function renderHTMLTreeLog(node, parentElement) {
  const div = document.createElement('div');
  div.className = 'log-entry';
  div.innerHTML = `
    <span class="log-message">${node.message}</span>
    <span class="log-time">${node.timestamp.toLocaleString()}</span>
  `;

  if (node.children.length > 0) {
    const childrenContainer = document.createElement('div');
    childrenContainer.className = 'log-children';
    node.children.forEach(child => {
      renderHTMLTreeLog(child, childrenContainer);
    });
    div.appendChild(childrenContainer);
  }

  parentElement.appendChild(div);
}

实用工具方法

提供搜索和过滤功能:

js实现treelog

function searchLogTree(node, predicate, results = []) {
  if (predicate(node)) {
    results.push(node);
  }

  node.children.forEach(child => {
    searchLogTree(child, predicate, results);
  });

  return results;
}

性能优化

对于大型日志树实现懒加载:

class LazyLogNode {
  constructor(message) {
    this.message = message;
    this._children = null;
  }

  get children() {
    if (this._children === null) {
      this._children = loadChildrenFromServer(this.id);
    }
    return this._children;
  }
}

示例CSS样式

配合HTML渲染的样式建议:

.log-entry {
  margin-left: 15px;
  padding: 5px;
  border-left: 1px solid #ddd;
}
.log-message {
  font-weight: bold;
}
.log-time {
  color: #666;
  font-size: 0.8em;
  margin-left: 10px;
}
.log-children {
  margin-left: 20px;
}

标签: jstreelog
分享给朋友:

相关文章

js实现验证

js实现验证

验证表单输入 使用JavaScript验证表单输入是常见的需求。可以通过监听表单提交事件,检查输入字段是否符合要求。 document.getElementById('myForm').addEve…

js实现换肤

js实现换肤

使用CSS变量实现换肤 通过CSS变量可以轻松实现主题切换功能。CSS变量在根元素中定义,通过JavaScript动态修改这些变量值。 :root { --primary-color: #349…

js 实现链表

js 实现链表

链表的基本概念 链表是一种线性数据结构,由一系列节点组成,每个节点包含数据和指向下一个节点的指针。与数组不同,链表在内存中是非连续存储的,插入和删除操作效率较高。 链表的实现 在 JavaScrip…

js实现vue路由

js实现vue路由

Vue 路由的基本实现 在 Vue.js 中实现路由功能通常使用 Vue Router 库。Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。 安装 Vue R…

js实现密码

js实现密码

密码强度验证 使用正则表达式验证密码强度是一种常见方法。以下代码检查密码是否包含大小写字母、数字和特殊字符,且长度至少为8位: function checkPasswordStrength(pass…

js实现正交

js实现正交

正交的概念 正交在数学和计算机科学中通常指两个向量垂直或线性无关。在编程中,正交性常被用于设计模块化、低耦合的系统。 向量正交判断 判断两个向量是否正交可以通过点积是否为0来实现: fun…