码迷,mamicode.com
首页 > 其他好文 > 详细

递归中,调用forEach方法问题

时间:2018-01-06 14:27:25      阅读:79      评论:0      收藏:0      [点我收藏+]

标签:提示   col   return   ==   fun   val   9.png   foreach   body   


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方法问题

标签:提示   col   return   ==   fun   val   9.png   foreach   body   

原文地址:https://www.cnblogs.com/tangwanzun/p/8213652.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!