js遍历数组 循环json数组

JS数组的遍历方法有两种:

一:一般的for循环,例如:

1

2

3

4

var a = new Array("first", "second", "third")

for(var i = 0;i < a.length; i++) {

document.write(a[i]+",");

}

输出的结果:fitst,second,third

二:用for...in 这种遍历的方式,例如:

1

2

3

4

var arr = new Array("first", "second", "third")

for(var item in arr) {

document.write(arr[item]+",");

}

输出的结果:fitst,second,third

 

jQuery 遍历json数组的实现代码

一、使用each遍历

  var obj = [{ "name": "张三丰", "password": "123456"}];
     alert(obj); //是个object元素
    //下面使用each进行遍历
    $.each(obj, function (n, value) {
        alert(n + ' ' + value);
        var trs = "";
        trs += "" + value.name + " " + value.password + "";
       tbody += trs;
    });

又例如:

    var d1 =[{"text":"一年级","value":"9"},
             {"text":"二年级","value":"10"},
             {"text":"三年级","value":"13"}
            ];
    $(d1).each(function(){
           alert(this.text+" "+this.value);
       });

 

二、jquery遍历解析json对象:

 var json = [{dd:'SB',AA:'东东',re1:123},{cccc:'dd',lk:'1qw'}];
 for(var i=0,l=json.length;i

三、jquery遍历解析json对象:

var obj ={”name”:”冯娟”,”password”:”123456″,”department”:”技术部”,”sex”:” 女”,”old”:30};
for(var p in obj){
    str = str+obj[p]+',';
    return str;
}

js中json与对象的转换

一:JSON字符串转为JS对象

var jsonObj1 = JSON.parse(data);  //使用JSON.parse() 将JSON字符串转为JS对象;
var jsonObj2 = eval('(' + data + ')'); //使用eval() 将JSON字符串转为JS对象;

var json = '[
             {"id":"1","tagName":"apple"},
             {"id":"2","tagName":"orange"},
             {"id":"3","tagName":"banana"},
             {"id":"4","tagName":"watermelon"},
             {"id":"5","tagName":"pineapple"}
            ]';


$.each(JSON.parse(json), function(idx, obj) {
    alert(obj.tagName);
});

//or

$.each($.parseJSON(json), function(idx, obj) {
    alert(obj.tagName);
});


二 : 对象转为JSON字符串

var json = {"name":"iphone","price":666}; //创建对象;
var jsonStr = JSON.stringify(json);       //转为JSON字符串
console.log(jsonStr);

 

你可能感兴趣的:(数据)