for循环里面的循环函数在javascript中

时间:2015-09-11 23:48:06

标签: javascript

我有一个for循环,它应该遍历一个对象。但是这个对象里面可以有很多其他对象级别。我如何创建一个函数,使for循环内的lvl循环循环到我想要的多个深度?

这样的事情,var lvl = 5; for (var i = 0; i < groups.length; i++) { var groups = groups[i]; for (var i = 0; i < groups.length; i++) { var groups = groups[i]; for (var i = 0; i < groups.length; i++) { var groups = groups[i]; } } } 变量将是它应该潜入的等级数量:

var foo = {
  child: {
    grand:{
      greatgrand: {
      }
    }
  }
}

例如,如果我有以下对象树:

foo

如何通过跳转到dive(2); // would dive to level two (grand) // would return the following in the console child grand 对象中的特定级别来控制记录所有对象树名称?

{{1}}

2 个答案:

答案 0 :(得分:2)

递归函数 - 一个自我调用的函数 - 是要走的路。你想要这样的东西:

/* pseudo-code; this will not run */
function processThing(thing) {
  if (thing is an object) {
    // process all of thing's properties
    for (property in thing) {
      processThing(property);
    }
  }
  else {
    // process thing as a value
  }
}

答案 1 :(得分:2)

你走了。我编写了一个递归函数,它将迭代一个对象图。您可以为遍历函数提供深度参数。

JSFiddle是here。请检查开发人员工具控制台以获取输出 添加缩进的小提琴是here

var obj = {
firstName: "John",
lastName: "Doe",
address1A: {
    street: "120 Washington St",
    city: "Mountain View",
    state: "CA",
    address2A: {
        street: "100 Washington st",
        city: "Mountain View",
        state: "CA",
        address3A: {
            street: "150 Washington st",
            city: "Mountain View",
            state: "CA",
            address4A: {
                street: "150 Washington st",
                city: "Mountain View",
                state: "CA",
            }
        }
    }
},
address1B: {
    street: "120 Washington St",
    city: "Mountain View",
    state: "CA",
    address2B: {
        street: "100 Washington st",
        city: "Mountain View",
        state: "CA",
        address3B: {
            street: "150 Washington st",
            city: "Mountain View",
            state: "CA",
            address4B: {
                street: "150 Washington st",
                city: "Mountain View",
                state: "CA",
            }
        }
    }
}
};

function traverse(initObj, depth) {
     depthTraversal(initObj, depth, 1);
}

function depthTraversal(objArg, depthArg, counterArg) {
    //create a closure for remembering loop variables
    return (function (myObj, myDepth, counter) {
        //console.log(myDepth + " - " + counter);
        if (myDepth < counter) {
          return;
        }
       //console.log(myObj);
       for (var prop in myObj) {
          //console.log(prop + " :" + typeof (myObj[prop]));
          if (myObj.hasOwnProperty(prop)) {
             if (typeof (myObj[prop]) === "object") {
                console.log(prop);
                depthTraversal(myObj[prop], myDepth, counter + 1);
             }
          }
      }
}(objArg, depthArg, counterArg)); //IIFE
};


traverse(obj, 4);