遞歸中,調用forEach方法問題
阿新 • • 發佈:2018-01-06
argument http pre 遞歸 沒有 一個 溢出 col pic
1 function traverse(objNmae,obj,url){ 2 url = url || objNmae; 3 if(typeof obj === "object" ){ 4 //for in 方法 5 for(let i in obj){ 6 url += ("=>"+i); 7 arguments.callee(i,obj[i],url); 8 } 9 //forEach 方法 10 obj.forEach(function(value,index){ 11 url += ("=>"+index); 12 arguments.callee(index,value,url); 13 }); 14 }else if(typeof obj === "string" || typeof obj === "number"){ 15 console.log(url+objNmae+":"+obj);16 return; 17 } 18 }
for in 方法 和forEach方法,方法的功能是同樣的,就是遍歷一個對象集,並且輸出對象中所有末端元素的路徑。
接下來我們對下面的這個對象進行遍歷
var itg_data = [{"itg_num":"1200","itg_category":"rew_gold","itg_reward_num":"1","itg_sum_num":"661","itg_place":"","pic":"\/Uploads\/game\/reward\/357203060783037259.png","goods_unit":"\u679a","goods_name":null},{"itg_num":"1400","itg_category":"rew_goods","itg_reward_num":"4","itg_sum_num":"656","itg_place":"fresh","pic":"\/Uploads\/UploadsShop\/2017-07-05\/595c823c86cf7.jpg","goods_unit":"\u679a","goods_name":"\u65e0\u6297\u571f\u9e21\u86cb"},{"itg_num":"1600","itg_category":"rew_gold","itg_reward_num":"2","itg_sum_num":"555","itg_place":"","pic":"\/Uploads\/game\/reward\/357203060783037259.png","goods_unit":"\u679a","goods_name":null},{"itg_num":"1800","itg_category":"rew_goods","itg_reward_num":"8","itg_sum_num":"492","itg_place":"fresh","pic":"\/Uploads\/UploadsShop\/2017-07-05\/595c823c86cf7.jpg","goods_unit":"\u679a","goods_name":"\u65e0\u6297\u571f\u9e21\u86cb"},{"itg_num":"2500","itg_category":"rew_goods","itg_reward_num":"1","itg_sum_num":"555","itg_place":"fresh","pic":"\/Uploads\/UploadsShop\/2017-06-22\/594b602919d9d.jpg","goods_unit":"\u53ea","goods_name":"\u6bcd\u9e21\uff08\u6563\u517b\uff09"}];
for in 方法
但是在這裏 forEach方法會報錯,
提示最大調用棧大小超過。但是使用for in 就沒有這樣的問題
由此可見,forEach在遞歸中因為,有些對象樹過深,對導致其堆棧溢出,forEach不適合用在遞歸中,可以使用for in
遞歸中,調用forEach方法問題