我们将编写一个递归函数。递归意味着它将再次执行自己:
function iterate(obj) {
// we will write the parent and the name
console.log(obj.parent + ' | ' + obj.name);
// if it has children
if (obj.children.length) {
// for each child
for (var i = 0, l = obj.children.length; i < l; i++) {
// we will call this function again
arguments.callee(obj.children[i]);
}
}
}
现在,如果我们有这样的对象:
var obj = {
name: 'P1',
parent: undefined,
children: [
{
name: 'P2',
parent: 'P1',
children: []
},
{
name: 'P3',
parent: 'P1',
children: [
{
name: 'P4',
parent: 'P3',
children: [
{
name: 'P5',
parent: 'P4',
children: []
}
]
}
]
},
{
name: 'P6',
parent: 'P1',
children: []
}
]
};
我们可以遍历它:
iterate(obj);
FIDDLE DEMO(在浏览器中打开您的控制台)