首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

怎么遍历对象属性并返回值

2013-07-04 
如何遍历对象属性并返回值?如有对象a {name:text,childrenElm:{parentID:0,myName:john,aihao:{web:

如何遍历对象属性并返回值?
如有对象
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 getAttrVay(obj[i],attrName)                


     }else{
       if (i == attrName){                
         return obj[i];                
       }    
     }    
  }
}


[解决办法]

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> new document </title>
<style type="text/css">
#aa {

}
</style>
</head>

<body>
<script type="text/javascript">

function Assessment(){
this.sex = null;
this.married = null;
this.age = 20;
this.address = {
provinces:0,
city:0
};
this.houseState = null;
this.houseCosts = null;
this.familyStructure = {
toddlers:0,
elementary:0,
teenager:0,
movedOut:0,
movedBackIn:0
};
this.familyCost = null;
this.payForEducation = null;
this.loans = {
factors:{
auto:0,
personal:0,
education:0,
otherA:0
},
attachedFactors:{
charities:0,
special:0,
elders:0,
otherB:0
},
lowerFactionrs:{
cash:0,
savings:0,
insurance:0,
otherC:0
}

}
function getAttrVay(obj, attrName)
{
   for(var i in obj){
     if(obj[i] instanceof Object){                
       var s = getAttrVay(obj[i],attrName);
       if(s!==undefined) return s;
     }else{
       if (i == attrName){
         return obj[i];                
       }    
     }    
  }
}
var a = new Assessment();
alert(getAttrVay(a, "auto"))

热点排行