首页 > 代码库 > js计算之递归

js计算之递归

看以下js代码:

var w = [{
        label: ‘你好‘,
        node: [
            {
                label: ‘你好啊‘,
                node: [{
                    label: "还好",
                    node: []
                }, {
                    label: ‘你好吧‘,
                    node: []
                },{
                    label: "还好",
                    node: []
                }, {
                    label: ‘你好吧‘,
                    node: [
                        {
                            label: "还好",
                            node: []
                        }, {
                            label: ‘你好吧‘,
                            node: []
                        }
                    ]
                }]
            }
        ]
    },
        {
            label: ‘我来了‘,
            node: []
        }
    ]

  怎么找出上面所有的label值,上面就是一个树型结构;

用递归遍历里面的所有对象如下:

    var b = [];
    function digui(c) {
        for (var i = 0; i < c.length; i++) {
            if (c[i].node.length === 0) {
                b.push(c[i].label)
            } else {
                b.push(c[i].label)
                digui(c[i].node)
            }
        }
    }
    digui(w)
    console.log(b);

js计算之递归