【问题标题】:Print object properties using recursion使用递归打印对象属性
【发布时间】:2021-12-10 03:09:06
【问题描述】:

我需要帮助编写一个 javascript 函数,该函数获取一个类作为参数,并使用带有缩进的反射打印​​其所有公共属性(名称和值)。

一些属性可以是类类型,因此需要使用正确的缩进打印属性。

例子:

Class A {
  a1;
  a2;

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


Class B {
  b1;
  b2;

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

当获取class B 作为参数时,输出应该是:

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

谢谢!

【问题讨论】:

    标签: javascript object recursion


    【解决方案1】:

    您可以使用递归函数以递归方式返回格式化字符串,

    class A { a1 = 'a'; a2 = 2; }
    class B { b1 = true; b2 = new A; }
    
    function format(object, indent_lvl = 1) {
        let str = "Object:\n" + "\t".repeat(indent_lvl - 1) + "----------------------------------------";
        let indent = "\n" + "\t".repeat(indent_lvl);
        for (let [key, value] of Object.entries(object)) {
            if (typeof value == "object")
                value = indent + format(value, indent_lvl + 1);
    
            str += indent + key + " = " + value;
        }
        return str;
    }
    
    console.log(format(new B))

    【讨论】:

      猜你喜欢
      • 2011-09-05
      • 2018-04-20
      • 2021-01-01
      • 2020-11-18
      • 2020-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-19
      相关资源
      最近更新 更多