JavaScript 深度遍历对象的两种方式,递归与非递归

递归遍历:

  • 基本问题: 当前属性值不为对象时,打印键和值
  • 递归过程:当前属性值为对象时,打印键,继续递归
var o = {
            a: {
                b: {
                    c: {
                        d: {
                            e: {
                                f: 1,
                                g:{
                                    h:2
                                }
                            }
                        }
                    }
                }
            }
        };
        function printObjRec(obj) {
            for (var prop in obj) {
                if (typeof (obj[prop]) === "object") {
                    console.log(prop);
                    getProp(obj[prop]);
                    return;
                }
                console.log(prop);
                console.log(obj[prop]);
            }
        };
        // printObjRec(o);

非递归遍历:

猜你喜欢

转载自www.cnblogs.com/ltfxy/p/12334116.html