繁体   English   中英

嵌套注释的递归javascript

[英]Recursive javascript for nested comments

我正在尝试递归遍历嵌套的注释数据,例如...

-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

(缺少“儿童评论b”)

因此,看来递归调用正在工作,但是当递归调用完成时javascript不会恢复以前的位置?

可以肯定的是,我缺少关于递归循环在javascript中工作的方式的一些基本知识,但是在进行了一些研究并尝试了各种解决方案后无济于事,我不知道该怎么办。 感谢您的任何想法!

为了使递归如此工作,必须将k变量声明为局部变量。 否则,它是一个隐式全局变量,并且对该函数的每个递归调用都将覆盖调用者正在使用的变量的值,因此当您从递归调用返回时,父调用者中的k值已被破坏并且其循环无法执行它应该做什么。 请参阅此处添加到k定义的var

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的不良功能。 使用严格模式来防止它们。

题。 在运行循环时,在if属性中,您尝试比较输入的数据与正在循环的文件。

您将如何比较为搜索文件而输入的数据?

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

输入的数据== filegiven(已存储数据,需要进行比较)。长度或值? 要么.....?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM