javascript - 怎么递归输出这个对象?
巴扎黑
巴扎黑 2017-04-10 14:23:07
0
3
367
var orz = {
    it: {
        facebook: {
            apple: {
                google: {
                    twitter: {}
                },
                microsoft: {}
            }
        }
    },
    china: {}
};

function objLength(obj) {
    var j = 0;
    for (i in obj) {
        j++;
    }
    return j;
}

function re(ja, num, tree, jn) {
    if (objLength(ja) == 0) {
        return;
    }
    if ("undefined" == typeof num) {
        num = 0;
    }
    if ("undefined" == typeof tree) {
        tree = [];
    }
    if ("undefined" != typeof jn) {
        tree.push(jn);
    }
    num++;
    fo(ja, tree, num);

    function fo(a, b, c) {
        for (x in a) {
            if (b.length > 0) {
                console.log(c + ": " + b + "," + x);
            } else {
                console.log(c + ": " + x);
            }
            re(a[x], c, b, x);
        }
    }
}

re(orz);

/**
 * 为什么结果是:
 * 1: it
 * 2: it,facebook
 * 3: it,facebook,apple
 * 4: it,facebook,apple,google
 * 5: it,facebook,apple,google,twitter
 * 4: it,facebook,apple,google,microsoft
 * 1: it,facebook,apple,google,china
 * 而不是
 * 1: it
 * 2: it,facebook
 * 3: it,facebook,apple
 * 4: it,facebook,apple,google
 * 5: it,facebook,apple,google,twitter
 * 4: it,facebook,apple,microsoft
 * 1: china
 *
 */
修改
巴扎黑
巴扎黑

全員に返信(3)
阿神
var orz = {
    it: {
        facebook: {
            apple: {
                google: {
                    twitter: {}
                },
                microsoft: {}
            }
        }
    },
    china: {}
};

var result = [];

function re(obj, prev) {
    Object.keys(obj).forEach(function(item) {
        var hehe = '';
        if (obj[item] instanceof Object && !(obj[item] instanceof Array)) {
        //如果数组也算,使用下边的条件
        //if (obj[item] instanceof Object) {
            hehe = (prev.length ? prev + ',' + item : item);
            result.push(hehe);
            re(obj[item], hehe);
        }
    });
}
re(orz, '');
console.log(result);
いいねを押す +0
Peter_Zhu

因为你用了push,所以当循环遍历到google时,tree为["it", "facebook", "apple", "google"],接下来console输出的三个记录就是:
5: it,facebook,apple,google,twitter
4: it,facebook,apple,google,microsoft
1: it,facebook,apple,google,china
解决方法有两个:
1.push后进行pop操作

num++;
fo(ja, tree, num);
tree.pop(jn);

2.使用String代替Array

tree += jn;
いいねを押す +0
伊谢尔伦
var orz = {
    it: {
        facebook: {
            apple: {
                google: {
                    twitter: {}
                },
                microsoft: {}
            }
        }
    },
    china: {}
};

var re=function(current,path){
    for(var c in current){
        path.push(c);
        console.log(path.length + ":"+ path.join(","));
        re(current[c],path);
        path.pop();
    }
}

re(orz,[]);
いいねを押す +0
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート