我正在开发一个treeview,并构建了一个简单的节点类:它由一个名称和一个子数组组成:
class Node {
constructor(name, childNodes) {
this.name = name;
this.childNodes = childNodes;
}
}
现在,我的目标是创建一个返回如下对象的函数:
var tree = [
{
text: 'Parent 1',
nodes: [
{
text: 'Child 1',
nodes: [
{
text: 'Grandchild 1'
}
]
},
{
text: 'Child 2'
}
]
},
{
text: 'Parent 2'
},
];
我尝试使用递归方法。它从一个空数组开始并添加子数组,直到没有剩余的子数组为止:
function recTreeview(currentNode, treeview) {
var tempChildren = [];
currentNode.childNodes.forEach(child => {
tempChild.push(recTreeview(child, treeview));
});
return treeview.push({
text: currentNode.name,
nodes: tempChildren
})
}
但是递归Treeview函数肯定有问题。当我创建树并尝试在chrome开发控制台中打开它时,它只显示一个“5”,而不是(5)[{}、{}、{}、{}、{}、{}、{}、{}、{}、{})。我做错了什么?
tree = recTreeview(parent, []);
tree;