嵌套注释的递归javascript

时间:2016-05-08 16:52:42

标签: javascript recursion

我试图以递归方式遍历嵌套的评论数据,例如...

-parent comment a
----child comment a
--------grandchild comment a
----child comment b
-parent comment b

以下是我在javascript中所做的事情的概述......

loadChildComments(commentdata[i].comment_id); //for every parent comment I make this call to load children

function loadChildComments(parentId){

  for (k=0; k<commentdata.length; k++) { //loop through the same data set looking for child comments
    if (commentdata[k].immediate_parent_id == parentId) {
      //we've found a child comment

      //bunch of steps to add the child comment to the page

      ///just finished adding a child comment so loop through to see if that child itself has children
      loadChildComments(commentdata[k].comment_id); //also tried arguments.callee(commentdata[k].comment_id);

    }
  }
  return true;
}

如果我不在最后添加递归回调到loadChildComments(),我正确地得到......

-parent comment a
----child comment a
----child comment b
-parent comment b

但是当我确实包含回调时,我得到了这个......

-parent comment a
----child comment a
--------grandchild comment a
-parent comment b

(缺少&#34;儿童评论b&#34;)

所以似乎递归调用正在运行,但是javascript在完成递归调用时没有找到它以前的位置?

我很确定我错过了一些关于递归循环在javascript中的工作方式的基本信息,但是在做了一些研究并尝试各种解决方案后无所谓。感谢任何想法!

2 个答案:

答案 0 :(得分:3)

对于这样的递归,您必须将k变量声明为局部变量。否则它是一个隐式全局,并且对函数的每次递归调用都会覆盖调用者正在使用的变量的值,因此当您从递归调用返回时,父调用者中的k的值已被销毁,并且循环无法做到它应该做的事情。请参阅此处var定义中添加的k

loadChildComments(commentdata[i].comment_id); //for every parent comment I make this call to load children

function loadChildComments(parentId){

  // <== Add var in front of k=0 in line below
  for (var k=0; k<commentdata.length; k++) { //loop through the same data set looking for child comments
    if (commentdata[k].immediate_parent_id == parentId) {
      //we've found a child comment

      //bunch of steps to add the child comment to the page

      ///just finished adding a child comment so loop through to see if that child itself has children
      loadChildComments(commentdata[k].comment_id); //also tried arguments.callee(commentdata[k].comment_id);

    }
  }
  return true;
}

如果您在严格模式下运行代码,那么这种类型的错误将是一个错误,运行时会立即指出它。隐式全局变量(当你未能声明变量时)是Javascript的一个不好的特性。使用严格模式来阻止它们。

答案 1 :(得分:0)

问题。在运行循环时,在if语句中,您试图比较输入的数据与循环的文件。

您如何比较输入的数据以搜索文件?

是.length还是.value?我被困在试图比较你回答确实回答了数组长度的问题,但我只是要求比较

输入数据== filegiven(存储和需要比较的数据).length或value?还是......?