以递归方式循环遍历对象(树) [英] looping through an object (tree) recursively

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

问题描述

是否有办法(在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...
} 

请注意,循环中的将迭代任何可枚举属性,包括那些被添加到对象的原型中。要避免对这些属性进行操作,可以使用 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天全站免登陆