递归中,调用forEach方法问题


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

 

posted @ 2018-01-06 11:05  兔子只吃胡萝卜  阅读(2025)  评论(0编辑  收藏  举报