You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript如何编写递归带缩进打印类公共属性的函数

实现方案

核心逻辑如下:

  • 首先对传入的类进行实例化,获取实例对象
  • 递归遍历实例的所有自身可枚举公共属性,每深入一层嵌套缩进加2个空格
  • 判断属性值类型:如果是自定义类实例则递归打印其内部属性,否则直接打印属性值

完整代码如下:

// 递归打印类实例属性的工具函数
function printClassProperties(Clazz, indentLevel = 0) {
  // 基础缩进,每层2个空格
  const indent = '  '.repeat(indentLevel);
  // 实例化传入的类
  const instance = new Clazz();

  // 打印当前对象头部
  console.log(`${indent}Object:`);
  console.log(`${indent}----------------------------------------`);

  // 遍历所有自身公共属性
  for (const [key, value] of Object.entries(instance)) {
    // 判断当前值是不是自定义类的实例(排除基础类型、普通对象、常用内置对象)
    const isClassInstance = typeof value === 'object' 
      && value !== null 
      && value.constructor !== Object 
      && !Array.isArray(value)
      && !(value instanceof Date)
      && !(value instanceof RegExp);

    if (isClassInstance) {
      // 是类实例,先打印属性名,再递归打印子属性,缩进+1
      console.log(`${indent}  ${key} = `);
      printClassProperties(value.constructor, indentLevel + 1);
    } else {
      // 普通值直接打印,字符串加双引号匹配示例格式
      const formattedValue = typeof value === 'string' ? `"${value}"` : value;
      console.log(`${indent}  ${key} = ${formattedValue},`);
    }
  }
}

// 示例类定义
class A {
  a1;
  a2;

  constructor() {
    this.a1 = 'a';
    this.a2 = 2;
  }
}

class B {
  b1;
  b2;

  constructor() {
    this.b1 = true;
    this.b2 = new A();
  }
}

// 测试调用,传入B类
printClassProperties(B);

运行后输出效果与需求预期一致:

Object:
----------------------------------------
  b1 = true,
  b2 = 
  Object:
  ----------------------------------------
    a1 = "a",
    a2 = 2,

如果需要适配其他内置对象类型,可在isClassInstance的判断逻辑中自行添加排除规则。

内容的提问来源于stack exchange,提问作者maya dahan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 14:36:01