遍历josn的三种方式
第一种:使用for循环
js代码:
- function CyclingJson1() {
- var testJson = '[{ "name": "小强", "age": 16 },{"name":"小明","age":17}]';
- testJson = eval("(" + testJson + ")");
- for (var i = 0; i < testJson.length; i++) {
- alert(testJson[i].name);
- }
- }
第二种:使用关键字in
js代码:
- function CyclingJson2() {
- var testJson = '[{ "name": "小强", "age": 16 },{"name":"小明","age":17}]';
- testJson = eval("(" + testJson + ")");
- for (var i in testJson) {
- alert(testJson[i].name);
- }
- }
第三种;使用jquery.each()函数
- function CyclingJson3() {
- var testJson = '[{ "name": "小强", "age": 16 },{"name":"小明","age":17}]';
- testJson = eval("(" + testJson + ")");
- $.each(testJson, function (i, n) {
- alert(i); //i为索引值
- alert(n.name); //n为遍历的值
- });
- }