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
相关产品推荐
相关产品推荐

