码迷,mamicode.com
首页 > Web开发 > 详细

json对象遍历输出key和value

时间:2018-12-07 14:41:43      阅读:331      评论:0      收藏:0      [点我收藏+]

标签:数组   pack   password   ack   iba   pass   str   规律   pac   

js遍历json对象
原生js遍历json对象

遍历json对象:

无规律:

<11script>

var json = [

  {dd:‘SB‘,AA:‘东东‘,re1:123},

  {cccc:‘dd‘,lk:‘1qw‘}

];

for(var i=0,l=json.length;i<l;i++){

  for(var key in json[i]){

    alert(key+‘:‘+json[i][key]);

  }

}

</script>

有规律:

1
2
3
4
5
6
7
8
9
10
11
12
13
packJson = [

{"name":"nikita", "password":"1111"},

{"name":"tony", "password":"2222"}

];

for(var p in packJson){//遍历json数组时,这么写p为索引,0,1

alert(packJson[p].name + " " + packJson[p].password);

}
也可以用这个:

1
2
3
4
5
for(var i = 0; i < packJson.length; i++){

alert(packJson[i].name + " " + packJson[i].password);

}
遍历json对象

1
2
3
4
5
6
7
myJson = {"name":"caibaojian", "password":"1111"};

for(var p in myJson){//遍历json对象的每个key/value对,p为key

alert(p + " " + myJson[p]);

}
有如下 json对象:

var obj ={"name":"冯娟","password":"123456","department":"技术部","sex":"女","old":30};

遍历方法:

1
2
3
4
for(var p in obj){
str = str+obj[p]+‘,‘;
return str;
}

json对象遍历输出key和value

标签:数组   pack   password   ack   iba   pass   str   规律   pac   

原文地址:https://www.cnblogs.com/iseaside/p/10082256.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!