日期:2014-05-16  浏览次数:20418 次

如何遍历对象属性并返回值?
如有对象
a = {
         name:"text",
         childrenElm:{
                   parentID:0,
                   myName:"john",
                   aihao:{
                            web:"html",
                             code:"js"
                    }
          }
}

我想通过一个方法  getAttrVal(attrName)  直接取得该属性的值
下面是刚才编写的,但是不能达到预期的效果,这写法会输出N次。


alert(getAttrVal("code"))

function getAttrVay(attrName)
{
var obj = a;
        for(var i in obj){
if(typeof(obj[i]) == "object" && obj[i] !== null){
getAttrVay(obj[i],attrName)
}else{
if (i == attrName){
return obj[i];
break;
}
}
}
}


------解决方案--------------------
a = {
         name:"text",
         childrenElm:{
                   parentID:0,
                   myName:"john",
                   aihao:{
                            web:"html",
                             code:"js"
                    }
          }
}

alert(getAttrVay(a, "code"))
 
function getAttrVay(obj, attrName)
{
   for(var i in obj){
     if(typeof(obj[i]) == "object" && obj[i] !== null){                
       return getAttrVa