Overview
Use the filter function to filter array elements.
This function passes at least two parameters: the array to be filtered and the filter function. The filter function must return true to retain the element or false to remove the element.
Parameters
array,callback,[invert]Array,Function,BooleanV1.0
array: Array to be filtered.
callback: This function will process each element of the array. The first parameter is the current element, and the second parameter is the element index value. This function should return a boolean value. Alternatively, this function can be set to a string, and when set to a string, is treated as a "lambda-form" (short form?), where a represents the array element and i represents the element index value. For example, "a > 0" represents "function(a){ return a > 0; }".
invert: If "invert" is false or set, the function returns the elements in the array that are returned true by the filter function. When "invert" is true, the set of elements that are returned false by the filter function is returned.
Example
Description:
Filter elements less than 0 in the array.
jQuery Code:
$.grep( [0,1,2], function(n,i){ return n > 0; });
Result:
[1, 2]
Description:
Exclude elements greater than 0 in the array, use the third parameters to exclude.
jQuery Code:
$.grep( [0,1,2], function(n,i){ return n > 0; }, true);
Result:
[0]
grep() method is used to filter array elements
grep(array,callback,invert)
array: array to be filtered ;
callback: Process each element in the array and filter the elements. This function contains two parameters. The first is the value of the current array element, and the other is the subscript of the current array element. , that is, the element index value. This function should return a boolean value. Alternatively, this function can be set to a string, and when set to a string, is treated as a "lambda-form" (short form?), where a represents the array element and i represents the element index value. For example, "a > 0" represents "function(a){ return a > 0; }"
invert: Boolean optional, default value false, value is true or false, if "invert" is If false or set, the function returns the elements in the array that are returned true by the filter function. When "invert" is true, the function returns the set of elements that are returned false by the filter function.
var arr=$.grep([0,1,2,3,4,5,6],function(n,i){ return n>2 });
The above example returns [3,4,5,6], but the value we give to invert is true, for example
var arr=$.grep([0,1,2,3,4,5,6],function(n,i){ return n>2 },ture);
So what is returned now is [0,1,2] , that is, the elements filtered out by the callback function.
The above is the detailed content of jQuery: Detailed explanation of the use of .grep(). For more information, please follow other related articles on the PHP Chinese website!