递归地遍历对象(树) [英] looping through an object (tree) recursively

查看:32
本文介绍了递归地遍历对象(树)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法(在 jQuery 或 JavaScript 中)循环遍历每个对象以及它的子对象和孙子对象等等?

Is there a way (in jQuery or JavaScript) to loop through each object and it's children and grandchildren and so on?

如果是这样……我也可以读一下他们的名字吗?

If so... can I also read their name?

示例:

foo :{
  bar:'',
  child:{
    grand:{
      greatgrand: {
        //and so on
      }
    }
  }
}

所以循环应该做这样的事情......

so the loop should do something like this...

loop start
   if(nameof == 'child'){
     //do something
   }
   if(nameof == 'bar'){
     //do something
   }
   if(nameof =='grand'){
     //do something
   }
loop end

推荐答案

您正在寻找 for...in 循环中:

You're looking for the for...in loop:

for (var key in foo)
{
    if (key == "child")
        // do something...
} 

请注意,for...in 循环将遍历任何可枚举的属性,包括添加到对象原型中的属性.为了避免对这些属性进行操作,您可以使用 hasOwnProperty 方法来检查该属性是否仅属于该对象:

Be aware that for...in loops will iterate over any enumerable properties, including those that are added to the prototype of an object. To avoid acting on these properties, you can use the hasOwnProperty method to check to see if the property belongs only to that object:

for (var key in foo)
{
    if (!foo.hasOwnProperty(key))
        continue;       // skip this property
    if (key == "child")
        // do something...
}

递归执行循环就像编写递归函数一样简单:

Performing the loop recursively can be as simple as writing a recursive function:

// This function handles arrays and objects
function eachRecursive(obj)
{
    for (var k in obj)
    {
        if (typeof obj[k] == "object" && obj[k] !== null)
            eachRecursive(obj[k]);
        else
            // do something... 
    }
}

这篇关于递归地遍历对象(树)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆