0

の配列がありcommentsます。これらのコメントの一部は、実際には 内の他のノードのサブコメントですcomments。すべてcommentにはnum_comments、、、parent_idおよびid属性があります。コメントの数が 0 より大きい場合、コメントにサブコメントがあることはわかっています。

サブコメントを親コメント内に配置し、サブコメントを配列から削除したいと考えています。外側の for ループが完了した後、配列内に子コメントが存在してはならずcomments、各子コメントはその親コメントの subcomments配列に移動されます。

問題は、このコードが実行された後、すべてのアイテムcommentsが削除され、次のようになることです。

未定義のプロパティ 'item' を読み取れません

(これは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.subcomments が配列として定義されていないということです。これにより、プッシュされないエラーが発生します。これが説明していないのは、配列から何も削除されていないことです。

    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

4

2 に答える 2

2

ループしている配列を編集するときは、十分に注意する必要があります。elementiを使用していて、それを配列から削除すると、以前は element だったものになりますi + 1。しかしその後、ループがインクリメントし、元々 element だったものをスキップしましたi + 1。ここでは、2 つの入れ子になったループがあり、どちらも変更中のリストを対象としているため、エラーはさらに複雑になります。

ここに、あなたが望むことをすると私が信じているいくつかのコードがあります。

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 = []
于 2011-12-13T09:19:11.883 に答える
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)
于 2011-12-14T04:18:27.913 に答える