js递归实现树结构

var treeData = {
        name: 'root',
        children: [{
            name: 'child1',
            children: [{
                name: 'child1_1',
                children: [{
                    name: 'child1_1_1'
                }]
            }]
        }, {
            name: 'child2',
            children: [{
                name: 'child2_1'
            }]
        }, {
            name: 'child3'
        }]
    };
    var strArr = [treeData.name];
    //递归渲染树结构,关键在于如何抽象出递归的参数,node(叶子节点) rootOrder(记录层级) fn(用于渲染每个节点)
    function goThroughTree(node, rootOrder, fn) {
        var children = node.children || [];
        if (children.length) {
            for (var i = 0; i < children.length; i++) {
                var item = children[i];
                var index = i + 1;
                var order = rootOrder ? rootOrder + '.' + index : index;
                fn(item, order);
                goThroughTree(item, order, fn);
            }

        }
    }
    goThroughTree(treeData, 0, function (item, order) {
        strArr.push('<div>')
        strArr.push(order);
        strArr.push(item.name);
        strArr.push('</div>');
    });
    document.write(strArr.join(''))

得到结果:
root
1child1
1.1child1_1
1.1.1child1_1_1
2child2
2.1child2_1
3child3