Jquery 遍历数组之grep()方法介绍

时间:2022-04-24
本文章向大家介绍Jquery 遍历数组之grep()方法介绍,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

grep()方法用于数组元素过滤筛选。

grep(array,callback,boolean);方法参数介绍。

array   ---待处理数组

callback  ---这个回调函数用来处理数组中的每个元素,并过滤元素,该函数包含两个参数,第一个参数是当前数组元素的值,第二个参数是当前数组元素的下标,返回值是一个布尔值。

下面是grep()方法的源代码:

    //grep函数,第三个参数表示是否根据fn的结果取反!  
    grep: function( elems, callback, invert ) {  
    var callbackInverse,  
    matches = [],  
    i = 0,  
    //保存数组个数  
    length = elems.length,  
    //对传入的第二个参数取反,true变成false,false变成true  
    //如果invert为false,即!inverse为true,那么直接把函数返回true的元素加入,所以期望callbackExpect的就是true  
    callbackExpect = !invert;  
    // Go through the array, only saving the items  
    // that pass the validator function  
    for ( ; i < length; i++ ) {  
    //如果invert是false,表示不取反,那么如果fn返回true,就直接加入进去matches数组  
    //获取回调函数结果的返回值的取反的结果  
    callbackInverse = !callback( elems[ i ], i );    //这句代码说明回调函数的返回值是bool
    if ( callbackInverse !== callbackExpect ) {  
    matches.push( elems[ i ] );  
    }  
    }  
    return matches;  
    }  

invert  ---默认值为false,当值为false时,grep()返回的数组是满足callback条件的数组,当值为true时,grep()方法返回的则是不满足callback条件的数组。

当invert的值为true时。代码如下:

        $(function () {
            var result = $.grep([0, 1, 2, 3, 4, 5, 6], function (value, index) {
                return value > 5;
            },true);
            alert(result);
    

result=[0,1,2,3,4,5]

当invert的值为false时。代码如下

      $(function () {
            var result = $.grep([0, 1, 2, 3, 4, 5, 6], function (value, index) {
                return value > 5;
            },false);
            alert(result);
        });

result=[6];

当invert的值不填时,默认为false.