jQuery的$.each循环的对象

1.最简单的对象

//最简单的对象  
 o = {  
    'name':"哈哈",  
    'age' : 30,  
    'level':"2b",  
    'sex' : '男'  
};  
$.each(o, function(key, value){  
    console.log(key, value);  
});  

输出结果

2.最基本的数组

  2.1

//最基本的数组  
var a = [3,4,5,6,7];  
$.each(a, function(key, value){  
    console.log(key, value);  
});  

输出结果:

2.2   each处理二维数组  

        var arr2 = [['a', 'aa', 'aaa'], ['b', 'bb', 'bbb'], ['c', 'cc', 'ccc']]
        $.each(arr2, function (i, item) {
            console.log("i_:"+i);
            console.log("item_:"+item);
        });

arr2为一个二维数组,item相当于取这二维数组中的每一个数组。
item[0]相对于取每一个一维数组里的第一个值   
alert(i)将输出为0,1,2,因为这二维数组含有3个数组元素
alert(item)将输出为  ['a', 'aa', 'aaa'],['b', 'bb', 'bbb'],['c', 'cc', 'ccc']

输出结果:

对此二位数组的处理稍作变更之后

var arr = [['a', 'aa', 'aaa'], ['b', 'bb', 'bbb'], ['c', 'cc', 'ccc']]      
  $.each(arr, function(i, item){      
       $.each(item,function(j,val){
         alert(j);
         alert(val);
     }); 
});    

alert(j)将输出为0,1,2,0,1,2,0,1,2

alert(val)将输出为a,aa,aaa,b,bb,bbb,c,cc,ccc

3.又像数组,又像对象(晕晕的,$.each不循环) 

  1. var arr = [];  
  2. arr['name'] = "helios";  
  3. arr['version'] = 'trunk';  
  4. console.log(arr, typeof arr);  
  5. console.dir(arr);  
  6. $.each(arr, function(key, item){  
  7.     console.log(key, item, item[key]);  
  8. });  
  9.   
  10. console.log( Object.prototype.toString.call(arr) );  
  11. console.log( arr.constructor , arr.constructor === Array);  
  12. console.log(arr && typeof(arr) === "object" && arr.constructor === Array);  

console.log(arr);

输出结果:

console.dir(arr);

输出结果:

$.each(arr, function (key, item) {
console.log(key, item, item[key]);
});

没有输出结果

4.两个对象

var a1 = [], b1 = {};  
console.log(typeof a1, typeof b1);  

输出结果

5.json 对象处理

       var s = [{
            'name': "哈哈",
            'age': 30,
            'level': "2b",
            'sex': '男'
        }, {
            'name': "嘿嘿",
            'age': 30,
            'level': "3b",
            'sex': '男'
        }];
        $.each(s, function (index, item) {
            console.log(index, item, item.name);
        });

输出结果:

 6.部分应用

$("img").each(function(){
var a = $(this).attr("src");
});
//遍历后存放到数组中。。要用的时候再根据需要取.
var arr = new Array();
$("img").each(function(index){
    arr.push($(this).attr("src"));
})
  
//调用..
for(var i in arr){
    console.log(arr[i]);
}

 

 

参考:https://zccst.iteye.com/blog/2153569

posted on 2019-01-03 11:43  欢笑一声  阅读(599)  评论(0)    收藏  举报

导航