【问题标题】:Extending an object with a tree-traversing method in javascript在javascript中使用树遍历方法扩展对象
【发布时间】:2011-02-09 02:49:05
【问题描述】:

我有一个自定义对象,其中包含一个数组(称为“子项”),其中将存储相同类型的对象,从而创建一棵树。
假设它看起来像这样:

function CustomObject(){
    if (this instanceof Topic) {
    this.text = "Test";
    this.children = [];
    } else
        return new CustomObject(); }

现在,我想向该对象添加一个“forAll”方法,该方法将以深度优先的方式对该树的所有元素执行作为参数提供的另一个函数。最好的方法是什么?

【问题讨论】:

    标签: javascript tree-traversal


    【解决方案1】:

    这样的?

    CustomObject.prototype.forAll = function(func) {
      // process this object first
      func(this);
    
      // then process children
      for (var i = 0; i < this.children.length; i++)
        this.children[i].forAll(func);
    }
    

    【讨论】:

    • 不幸的是,这似乎不起作用。它似乎只在第一个元素上执行,然后出现错误退出。可以在这里试用:dl.dropbox.com/u/118505/psychojs/p.html
    • @Piotr:您的错误似乎在这里:map.centralTopic.forAll(get_text()) -- get_text() 将立即调用该函数,但您应该将函数对象传递给forAll,所以您应该这样做@ 987654326@
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-05
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多