Home > Article > Web Front-end > Detailed explanation of jQuery.grep() function
jQuery.grep() function is used to filter the elements in the array using the specified function and return the filtered array.
The source array will not be affected, and the filtered results are only reflected in the returned result array.
This function belongs to the global jQuery object.
Syntax
jQuery 1.0 adds this static function.
jQuery.grep( array, function [, invert ] )
Parameters
Notes:
This function will iterate through the array elements and execute the filter function. It will provide two parameters to the function: one is the array element of the current iteration, and the other is the index of the current iteration element in the array.
If the invert parameter is not specified, or is false, the resulting array will contain all elements for which the function returns true. If the parameter invert is true, the resulting array will contain all elements for which the function returned false.
Return value
The return value of the jQuery.grep() function is of Array type and returns the result array filtered by the specified function.
Example & Description
The jQuery example code of jQuery.grep() function is as follows:
//在当前页面内追加换行标签和指定的HTML内容 function w( html ){ document.body.innerHTML += "<br/>" + html; } var arr = [ 10, 25, 3, 0, -3 , 20, 6, 8, 11 ]; function filter(value, index){ return value > 10; } var result = $.grep( arr, filter ); // 保留了所有大于10的元素 w( result ); // 25,20,11 var result2 = $.grep( arr, filter, true ); // 保留了所有不大于10的元素 w( result2 ); // 10,3,0,-3,6,8