jq杂项方法/工具方法----each() grep() map()

each() 用于循环数组 对象(单纯遍历)

返回 false 可提前停止循环。接受的参数是数组名和要执行的函数,函数参数为数组索引和当前元素。

var arr = [30, 40, 50,1 ,8];
    $.each(arr, function(i,item){
        console.log(i,item);
    });
    // i index
    //item 当前元素

 $.grep() 用指定的函数过滤数组中的元素,并返回过滤后的数组,不影响原数组。

 $.grep(arr,function(item,i){
        console.log(i,'-----',item);
    });

 map();

  $.map(arr, function(item,i){
        console.log(i,item);
    });
   

grep map 也可遍历对象和数组。

存在过滤功能。写法完全相同。不影响原数组。

grep只过滤并返回新数组。map可以再过滤的基础上进行运算。

grep map的回调函数,参数一是循环到的每个元素,参数二是下标。

过滤数组,返回数组中字符串

 arr = ['hello',50,'world',4,'tom'];
    var res = $.grep(arr, function(item){
        if(typeof item == 'string') return item;
    });
    console.log(arr);
    console.log(res);

 返回数组中奇数

   arr = ['hello',50,'world',4,'tom'];
    
    // 数组中奇数
    res2 =  $.grep(arr, function(item,i){
        if(i % 2 != 0) return item;
    });
    console.log(arr);
    console.log(res2);

对数组每个元素做计算并返回新数组
 arr = ['a',2,'b',4,6 ,'c'];
    res = $.map(arr,function(item){
        return item + 100;
    });
    console.log(arr);
    console.log(res);

对数组符合要求的元素做计算并返回新数组
arr = ['a',2,'b',4,6 ,'c'];
    res = $.map(arr,function(item){
        if(typeof item == 'number')
        return item + 100;
    });
    console.log(arr);
    console.log(res);

 over (●'◡'●)

文章地址:

https://www.cnblogs.com/sandraryan/

原文地址:https://www.cnblogs.com/sandraryan/p/11528047.html