2011-12-13 50 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)