2011-12-13 58 views
0

我有一个comments的数组。其中一些评论实际上是comments内其他节点的子评论。每个comment具有num_comments,parent_idid属性。我知道评论有子注释时,它的评论数量大于0.拼接错误的元素

我想把子注释放在它的父注释中,并从数组中删除子注释。外循环完成后,comments数组中不应有子注释,并且每个子注释都将移入其父注释的subcomments数组中。

的问题是,这段代码运行后,在comments每一个项目被删除,我也得到:

无法读取的不确定

财产“项目”(这是一个结果的comments为空)

下面是我遇到的麻烦的代码:

for comment in comments 
     if comment.item.num_comments > 0 
      comment.item.subcomments = [] unless comment.item.subcomments 
      for comment_second in comments # Goes through a second time to find subcomments for the comment 
       if comment_second.item.parent_id == comment.item.id 
        comment.item.subcomments.push(comment_second) 
        comments.splice(comments.indexOf(comment_second), 1) 

编辑:

答案下面没有工作,但它肯定是朝着正确方向迈出的一步。我混淆了一下代码,我认为发生的事情是temp_comment.item.subcomment s没有被定义为一个数组。 这会导致一个不会被推送的错误。这并没有解释什么是从数组中删除。

temp_comments = comments.slice(0) 
    for comment in comments 
     for comment_second in comments 
     temp_comment = temp_comments[temp_comments.indexOf(comment)] 
     temp_comment.item.subcomements = [] unless temp_comment.item.subcomments? 
     if comment_second.item.parent_id == comment.item.id 
      temp_comment.item.subcomments.push(comment_second) 
      temp_comments.splice(temp_comments.indexOf(comment_second), 1) 
    comments = temp_comments 

我得到了同样的错误消息之前

2日编辑:

错误实际上是[] is not a function

回答

2

你必须编辑阵列时非常小心你正在循环。如果您使用的是元素i,并将其从阵列中移除,那么您现在处于之前的元素i + 1。但是,循环增加,你跳过原来的元素i + 1。在这里,你在两个嵌套循环中,都在你正在修改的列表上,所以错误变得更加复杂。

这里有一些代码,我相信做你想要的。

temp_comments = comments.slice(0) 
for comment in comments 
    for comment_second in comments 
    if comment_second.item.parent_id == comment.item.id 
     comment.item.subcomments.push(comment_second) 
     temp_comments.splice(temp_comments.indexOf(comment_second), 1) 
comments = temp_comments 

在这里,我们已经创建了一个临时数组(comments.slice(0)为阵列浅表副本成语)和修饰,代替原来的。

编辑:我认为评论对象是为此设置的。为了解决这个问题,请在拼接前进行:

for comment in comments 
    comment.item.subcomments = [] 
+0

我更新了帖子 –

+0

@Jarred你有错误的行号?我怀疑没有任何东西会被删除,因为它错误并在它结束之前停止运行,所以comments = temp_comments永远不会发生。 –

+0

它发生在https://gist.github.com/d163b5d50d1747d671bc的第12行 –

0

您还在用Javascript思考我想。

这应该做同样的事情,更清楚。

# Add subcomments to all comments that have them 
for comment in comments when comment.item.num_comments > 0 
    comment.item.subcomments = (sub for sub in comments when sub.item.parent_id == comment.item.id) 

# Filter out comments that have parents 
comments = (comment for comment in comments when !comment.item.parent_id)