javascript - 递归 JavaScript : child->parent relationship

标签 javascript recursion

我正在尝试遍历父级->子级关系链,直到我们到达没有自己父级的父级。如果子对象有父对象,则我们将该父对象以及该父对象的任何父对象存储在数组中。如果父级没有父级,我们将存储一个空数组。

这里有一些伪 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/

相关文章:

javascript - Term.js - 页面向下滚动到带有终端的部分

javascript - JQuery 可拖动元素在 droppable.append(draggable) 上消失在 droppable 中

javascript - 无法在队列完成时检索 dropzone 节点?

python - 如何检查嵌套列表树的所有元素是否相同?

c - 我如何更改函数中的指针?

javascript - 将 google 脚本值传递给 javascript datepicker

javascript - 手动转到上一个状态时 $ionicHistory.backView 的状态不正确

c++ - C++中退出递归栈

c - 变量是如何递归存储在内存中的?

javascript - 带有递归 JavaScript 的闭包