我正在尝试遍历父级->子级关系链,直到我们到达没有自己父级的父级。如果子对象有父对象,则我们将该父对象以及该父对象的任何父对象存储在数组中。如果父级没有父级,我们将存储一个空数组。
这里有一些伪 JSON,显示了我想要的数据结构。
Node3 = { // Node 3
parent: { // Node 2
parent: { // Node 1
parent: null,
parentTree: []
},
parentTree: [Node1]
},
parentTree: [Node2, Node1]
}
这是到目前为止的构造函数和递归方法...
function Node(parent) {
this.parent = typeof parent !== 'undefined' ? parent : null;
}
Node.prototype.getParentTree = function() {
if(typeof this.parentTree === "undefined") {
if (this.parent !== null) {
this.parentTree = this.parent.getParentTree();
this.parentTree.push(this.parent);
} else {
this.parentTree = [];
}
}
return this.parentTree;
}
这是我测试该方法的方法:
var node1 = new Node();
var node2 = new Node(node1);
var node3 = new Node(node2);
node3.getParentTree();
当前方法的问题在于,node1、node2 和 node3 的parentTree 的长度都 === 2。当您检查parentTree 中的对象时,它们包含无穷大的子对象对。
最佳答案
this.parentTree = this.parent.getParentTree(); this.parentTree.push(this.parent);
这样,父级和子级的 parentTree
都引用同一个 Array 对象 - 因此您也将新节点附加到父级树中。
使用 slice
创建数组的副本:
return this.parentTree.slice(); // every time the getter is called
或
this.parentTree = this.parent.getParentTree().slice(); // only for manipulating
关于javascript - 递归 JavaScript : child->parent relationship,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21273604/