Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/456.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在javascript中使用树遍历方法扩展对象_Javascript_Tree Traversal - Fatal编程技术网

在javascript中使用树遍历方法扩展对象

在javascript中使用树遍历方法扩展对象,javascript,tree-traversal,Javascript,Tree Traversal,我有一个自定义对象,其中包含一个数组(称为“子对象”),在该数组中存储相同类型的对象,从而创建一个树。 假设它看起来是这样的: function CustomObject(){ if (this instanceof Topic) { this.text = "Test"; this.children = []; } else return new CustomObject(); } 现在,我想向这个对象添加一个“forAll”方法,它将以深度优

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

function CustomObject(){
    if (this instanceof Topic) {
    this.text = "Test";
    this.children = [];
    } else
        return new CustomObject(); }
现在,我想向这个对象添加一个“forAll”方法,它将以深度优先的方式对树的所有元素执行另一个作为参数提供的函数。最好的方法是什么?

像这样的

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);
}
CustomObject.prototype.forAll=函数(func){
//先处理这个对象
func(本);
//然后处理孩子
for(var i=0;i
不幸的是,这似乎不起作用。它似乎只在第一个元素上执行,然后带着错误退出。可以在这里尝试:@Piotr:您的错误似乎在这里:
map.centralTopic.forAll(get_text())
--
get_text()
将立即调用该函数,但您应该将函数对象传递给
forAll
,因此您应该执行
map.centralTopic.forAll(get_text)