js遍历数组 循环json数组

时间:2022-12-30 11:53:29

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 += "<tr><td>" + value.name + "</td> <td>" + value.password + "</td></tr>";
               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<l;i++){
    for(var key in json[i]){
        alert(key+':'+json[i][key]);
    }
 }

三、jquery遍历解析json对象:

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

通过标准JSON.parse()或jQuery 的 $.parseJSON 将其转换为JavaScript对象。

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);
});