javascript js:如何获取toString()来打印对象细节

umuewwlo  于 2023-05-21  发布在  Java
关注(0)|答案(1)|浏览(138)

下面是一个例子:

class Node {
  constructor(data = null, parent = null) {
    this.data = data;
    this.parent = parent;
    this.children = [];
  }

  appendChild(data) {
    this.children.push(new Node(data, this.root));
    return this.root;
  }

  toString() {
    return this.data;
  }
}

class NTree {
  constructor(data) {
    this.root = null;
  }

  addRoot(data) {
    this.root = new Node(data);
  }

  find(data) {
    if (this.root.data === data) {
      return this.root;
    }
  }

  appendChild(data) {
    this.root.appendChild(data);
  }

  toString() {
    console.log(this.root);
  }
}

const t = new NTree();
t.addRoot(1);
t.appendChild(2);
t.appendChild(3);
t.appendChild(4);

console.log(t);

输出如下所示:

NTree {
  root: Node { data: 1, parent: null, children: [ [Node], [Node], [Node] ] }
}

如何将上面的输出转换为:

NTree {
  root: Node { data: 1, parent: null, children: [ 2, 3, 4 ] }
}
gv8xihay

gv8xihay1#

就这样做:

console.log(JSON.stringify(t.root, null, 4));

相关问题