`
380071587
  • 浏览: 446941 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

遍历和添加json对象的属性 和 遍历普通js对象的属性

 
阅读更多

1. 遍历 json 对象的属性

<wbr></wbr>

//定义json对象
<wbr>var person= {<br><wbr><wbr>name: 'zhangsan',<br><wbr><wbr>pass: '123',</wbr></wbr></wbr></wbr></wbr>

<wbr>fn: function(){</wbr>

<wbr><wbr><wbr><wbr>alert(this.name+"的密码="+this.pass);</wbr></wbr></wbr></wbr>

<wbr><wbr>}<br><wbr>}<br><wbr>//遍历person属性包括方法,如果不想显示出方法,可用typeof(person[item])== <wbr>"function"来判断<br><wbr>for(var item in person){<br><wbr><wbr>alert("person中"+item+"的值="+person[item]);<br><wbr>}</wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr>

<wbr></wbr>

<wbr></wbr>

2.动态为 json对象 添加属性

需要 使用1中的 person对象

var copyPerson={} <wbr><wbr>//创建copyPerson对象,将person中的属性包括方法copy给该对象<br><wbr>for(var item in person){<br><wbr><wbr>copyPerson[item]= person[item]; <wbr><wbr>//这样循环就可以将person中的属性包括方法copy到copyPerson中了<br><wbr>}<br><wbr><br><wbr>for(var item in copyPerson){<br><wbr><wbr>alert("copyPerson中"+item+"的值="+person[item]);<br><wbr>}</wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr>

<wbr></wbr>

注意:使用 Ext.apply(copyPerson, person) 也可以将person中的所有属性包括方法 copy到 copyPerson中

<wbr></wbr>

3.遍历 普通js对象的 属性

<wbr></wbr>

//定义一个普通的js类,包含方法
<wbr>var p= function (){<br><wbr><wbr>this.name= '李四';<br><wbr><wbr>this.pass= '456';<br><wbr><wbr>this.fn= function(){<br><wbr><wbr><wbr>alert(this.name+"的密码="+this.pass);<br><wbr><wbr>}<br><wbr><br><wbr>}</wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr>

<wbr>var pp= new p(); <wbr><wbr>//生成一个p类的对象 pp<br><wbr><br><wbr>for(var item in pp){<br><wbr><br><wbr>//遍历pp对象中的属性,只显示出 非函数的 属性,注意不能 遍历 p这个类<br><wbr><wbr>if(typeof(pp[item])== "function")<br><wbr><wbr><wbr>continue;<br><wbr><wbr>alert("p对象中"+item+"的属性="+pp[item]);<br><wbr>}</wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr>

<wbr></wbr>

普通的 js对象 也可以copy,copy方法和 2.动态为 json对象 添加属性 思路一样

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics