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

Node.js:如何自定义toString()让对象打印时显示子节点数据

修改NTree输出格式,让children显示数据而非Node对象

现有Node.js代码如下:

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 ] }
}

解决方案

需要做两处关键修改:

1. 修复Node.appendChild的parent赋值错误

原代码中new Node(data, this.root)是错误的——Node实例不存在root属性,应该传入当前Node实例this作为parent,同时修正返回值:

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

2. 自定义Node的控制台输出格式

Node.js中console.log输出对象时,会调用util.inspect方法,我们可以通过Symbol.for('nodejs.util.inspect.custom')自定义输出内容,让children数组直接显示子节点的data:

[Symbol.for('nodejs.util.inspect.custom')]() {
  return `Node { data: ${this.data}, parent: ${this.parent ? this.parent.data : null}, children: [ ${this.children.map(c => c.data).join(', ')} ] }`;
}

修改后的完整代码
class Node {
  constructor(data = null, parent = null) {
    this.data = data;
    this.parent = parent;
    this.children = [];
  }

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

  toString() {
    return this.data;
  }

  // 自定义控制台输出格式
  [Symbol.for('nodejs.util.inspect.custom')]() {
    return `Node { data: ${this.data}, parent: ${this.parent ? this.parent.data : null}, children: [ ${this.children.map(c => c.data).join(', ')} ] }`;
  }
}

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: [ 2, 3, 4 ] }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 04:12:31