如何遍历对象属性并返回值?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何遍历对象属性并返回值?相关的知识,希望对你有一定的参考价值。
如有对象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]; 参考技术A 为什么我换了个对象就不行了呢 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(typeof(obj[i]) == "object" && obj[i] !== null) return getAttrVay(obj[i],attrName) else if (i == attrName) return obj[i]; var a = new Assessment(); alert(getAttrVay(a, "auto")) 参考技术B for(var i in obj) alert(i);JS遍历类json对象属性值,方便统一赋值
JS遍历类、json对象属性、值,
我们在页面,经常会接收后面或json返回的数据,要一个一个赋值,遍历json属性,可以方便给界面的控件赋值。
代码:
遍历js类
<script type="text/javascript">
//定义一个普通的js类,包含方法
var p= function ()
this.Id= 1;
this.Name= 'test1';
var pp= new p();
for(var item in pp)
if(typeof(pp[item])== "function")
continue;
console.log("p对象中"+item+"的属性="+pp[item]);
</script>
遍历Json对象
//遍历Json对象属性、值
<script type="text/javascript">
//定义一个jsonArray对象
var json = [ a: '121', b: 222, bb: 'vvv' , a: '122', b: 223, bb: 'ccc' ];
for (var i=0;i<json.length;i++)
console.log(json[i]);
var jsonItem = json[i];
for (var item in jsonItem)
//遍历pp对象中的属性,只显示出 非函数的 属性,注意不能 遍历 p这个类
if (typeof (jsonItem[item]) == "function")
continue;
console.log("p对象中" + item + "的属性=" + jsonItem[item]);
</script>
以上是关于如何遍历对象属性并返回值?的主要内容,如果未能解决你的问题,请参考以下文章