js遍历所有子树

<script>
    let tree = [{
            id: '1',
            title: '节点1',
            children: [{
                    id: '1-1',
                    title: '节点1-1'
                },
                {
                    id: '1-2',
                    title: '节点1-2'
                }
            ]
        },
        {
            id: '2',
            title: '节点2',
            children: [{
                id: '2-1',
                title: '节点2-1'
            }]
        }
    ]

    function treeForeach(tree, func) {
        tree.forEach((data) => {
            func(data)
            data.children && treeForeach(data.children, func) // 遍历子树
        })
    }
    treeForeach(tree, node => {
        console.log(node.title)
    })
</script>
posted @ 2021-09-08 08:48  Cupid05  阅读(124)  评论(0编辑  收藏  举报