为了账号安全,请及时绑定邮箱和手机立即绑定

怎么递归输出这个对象?

怎么递归输出这个对象?

慕妹3242003 2019-04-08 11:18:48
varorz={it:{facebook:{apple:{google:{twitter:{}},microsoft:{}}}},china:{}};functionobjLength(obj){varj=0;for(iinobj){j++;}returnj;}functionre(ja,num,tree,jn){if(objLength(ja)==0){return;}if("undefined"==typeofnum){num=0;}if("undefined"==typeoftree){tree=[];}if("undefined"!=typeofjn){tree.push(jn);}num++;fo(ja,tree,num);functionfo(a,b,c){for(xina){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**/修改
查看完整描述

2 回答

?
拉丁的传说

TA贡献1789条经验 获得超8个赞

varorz={
it:{
facebook:{
apple:{
google:{
twitter:{}
},
microsoft:{}
}
}
},
china:{}
};
varresult=[];
functionre(obj,prev){
Object.keys(obj).forEach(function(item){
varhehe='';
if(obj[item]instanceofObject&&!(obj[item]instanceofArray)){
//如果数组也算,使用下边的条件
//if(obj[item]instanceofObject){
hehe=(prev.length?prev+','+item:item);
result.push(hehe);
re(obj[item],hehe);
}
});
}
re(orz,'');
console.log(result);
                            
查看完整回答
反对 回复 2019-04-08
  • 2 回答
  • 0 关注
  • 350 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号