我有一个comments
的数组。其中一些评论实际上是comments
内其他节点的子评论。每个comment
具有num_comments
,parent_id
和id
属性。我知道评论有子注释时,它的评论数量大于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
我更新了帖子 –
@Jarred你有错误的行号?我怀疑没有任何东西会被删除,因为它错误并在它结束之前停止运行,所以comments = temp_comments永远不会发生。 –
它发生在https://gist.github.com/d163b5d50d1747d671bc的第12行 –