在這裏,你去。我已經編寫了一個遞歸函數來迭代一個對象圖。您可以爲遍歷函數提供深度參數。
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);
你應該看看 – Jan
你需要不同的變量對每個嵌套'for'循環,這樣一個循環不是從別人覆蓋變量或者你可以做一個函數的遞歸函數做循環並遞歸地調用它。 – jfriend00
你有數組或對象嗎? – epascarello