Home > Web Front-end > JS Tutorial > Introduction to jquery array filtering method grep()_jquery

Introduction to jquery array filtering method grep()_jquery

WBOY
Release: 2016-05-16 16:45:35
Original
1549 people have browsed it

There is a grep() method in jquery for filtering array elements. Unfortunately, this description cannot be found in the API documentation we usually use. View the official instructions: http://api.jquery.com/jQuery.grep/


How to use grep():

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 false or set, the function returns the element in the array that is returned true by the filter function. When "invert" is true, Returns the set of elements that return false in the filter function.

After explaining the usage of grep(), let’s give a small example:

Copy code The code is as follows:
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
Copy code The code is as follows:
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], which is the element filtered out by the callback function.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template