【问题标题】:CoffeeScript: How to iterate through many levels of recursive data?CoffeeScript:如何遍历多层递归数据?
【发布时间】:2013-01-13 13:11:51
【问题描述】:

我的 cmetsArray

中有许多级别的嵌套 cmets

(这是从 API 中提取的,无法更改)

commentsArray = [
    {
        author: "jeff"
        replies: [
            {
                author: "jeff"
                replies: [
                    {
                        author: "simon"
                    }
                ]
            },
            {
                author: "simon"
            }
        ]
    },
    {
        author: "simon"
    }
]

我还有一个递归函数,dialogueParse,如果有问题的对象有“replies

,它会调用自己
dialogueParse = (comment) ->
    for child in comment
        if child.author is "simon"
            console.log "Simon was found.."

        if child.replies
            dialogueParse child

但是,此代码似乎无法正常工作。在我最初调用该函数后:

dialogueParse commentsArray

..由于某种原因,只找到位于第一级(数组末尾)的那个。

simon”在 3 个不同的地方被列为作者。

我已经为此工作了几个小时,但一无所获。任何帮助都非常感谢! :)

【问题讨论】:

    标签: javascript recursion coffeescript


    【解决方案1】:

    您不应该将child.replies 作为递归参数传递吗?

    如:

    dialogueParse = (comment) ->
        for child in comment
            if child.author is "simon"
                console.log "Simon was found.."
    
            if child.replies
                dialogueParse child.replies
    

    【讨论】:

    • 哇,这么简单的错误……显然我需要睡觉了。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-23
    • 2011-09-08
    • 1970-01-01
    相关资源
    最近更新 更多