Jquery的each和map方法使用~

175 阅读2分钟

「这是我参与11月更文挑战的第21天,活动详情查看:2021最后一次更文挑战

each方法

示例一:

    var arr=[1,3,5,7,9];
    var obj={0:1,1:3,2:5,3:7,4:9,length:5};
  • 第一个参数(value):遍历到的元素
  • 第二个参数(index):当前遍历元素的索引
  • 注意点:原生的Each只能遍历数组,不能遍历伪数组
    arr.forEach(function(value,index){
        console.log(index,value);
    })

结果:

image.png

示例二:

  • 该方法不能遍历伪数组
  • 错误信息提示:Uncaught TypeError: obj.forEach is not a function(无法找到obj的forEach方法)
     obj.forEach(function(value,index){
         console.log(index,value);
     })

示例三:利用jQuery的each静态方法遍历数组

  • 第一个参数(index):当前遍历元素的索引
  • 第二个参数(value):遍历到的元素
  • 注意点:jQuery的each可以遍历伪数组
        $.each(arr,function(index,value){
            console.log(index,value);
        });

        $.each(obj,function(index,value){
            console.log(index,value);
        });

结果:

image.png

map方法

示例一:

  • 第一个参数(value):遍历到的元素
  • 第二个参数(index):当前遍历元素的索引
  • 第三个元素(array):当前被遍历的数组
  • 注意点:和原生的forEach一样,不能遍历伪数组
     arr.map(function(value,index,array){
         console.log(index,value,array);
     });

结果:

image.png

        obj.map(function(value,index,array){
            console.log(index,value,array);
        });

结果:

错误信息提示:Uncaught TypeError: obj.map is not a function(无法找到obj的map方法)

示例二:

  • 第一个参数:要遍历的数组

  • 第二个参数:每遍历一个元素之后要执行的回调函数

    • 回调函数参数:
    • 第一个参数(value):遍历到的元素
    • 第二个参数(index):当前遍历元素的索引
  • 注意点:和jQuery中的each静态方法一样,map静态方法也可以遍历伪数组

        $.map(arr,function(value,index){
            console.log(index,value);
        });

        var res=$.map(obj,function(value,index){
            console.log(index,value);
            return index+value;
        });

        var res2=$.each(obj,function(index,value){
            console.log(index,value);
        });
        
        console.log(res);
        console.log(res2);

结果:

image.png

总结:jQuery中的each静态方法和 map静态方法的区别

  1. each静态方法默认的返回值是,遍历谁就返回谁
  2. map静态方法的返回值是一个空数组
  3. each静态方法不支持在回调函数中对遍历的数组进行处理操作
  4. map静态方法可以回调函数中用return对遍历数组进行操作,然后返回一个新的数组返回