【发布时间】:2012-01-19 01:38:07
【问题描述】:
我有一个comments 数组。其中一些 cmets 实际上是 comments 内其他节点的子 cmets。每个comment 都有一个num_comments、parent_id 和id 属性。我知道当评论的 cmets 数量大于 0 时,评论有 subcmets。
我想将子注释放在它的父注释中,并从数组中删除子注释。外部 for 循环完成后,comments 数组中应该没有子 cmets,并且每个子 cmets 都被移动到其父注释的 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.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
我收到与以前相同的错误消息
第二次编辑:
错误其实是[] is not a function
【问题讨论】:
标签: arrays loops coffeescript client-side-scripting