一道算法题,有会的可以一起讨论下

const data = {

    name: 'A',
    child: [{
            name: 'AB',
            child: [{
                    name: 'AABA'
                },
                {
                    name: 'AABB'
                }
            ]
        },
        {
            name: 'AC',
            child: [{
                    name: 'AACA'
                },
                {
                    name: 'AACB'
                }
            ]
        }
    ]
}
// 请自行封装一个findPath的函数,实现如下效果
// 调用示例

findPath('AABB'); //["A", "AB", "AABB"]

findPath('AABA'); //["A", "AB", "AABA"]

findPath('AACB'); //["A", "AC", "AACB"]

findPath('AC'); //["A", "AC"]

findPath('AACA'); //["A", "AC", "AACA"]

阅读 535
评论 2019-04-07 提问
    4 个回答
    柯楠
    • 655
    function findPath(obj, path) {
        var ret = [];
        var name = obj.name;
        var child = obj.child;
        check: if (name === path) {
            ret.push(name);
            break check;
        } else if (Array.isArray(child)) {
            for (var i = 0; i < child.length; i++) {
                var item = child[i];
                var tmp = findPath(item, path);
                if (tmp.length) {
                    ret = Array.prototype.concat.apply(ret, [name, tmp]);
                    break check;
                }
            }
        }
        return ret;
    }
    console.log(findPath(data, "AABB"));
    评论 赞赏 2019-04-07