Home > Web Front-end > JS Tutorial > The grep() method implements array filtering

The grep() method implements array filtering

php中世界最好的语言
Release: 2018-04-24 09:36:12
Original
2346 people have browsed it

This time I will bring you the grep() method to implement arrayFiltering and filtering, the grep() method to implement array filtering and screeningWhat are the precautions, the following is a practical case, one Get up and take a look.

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, which, 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, the default value is false, the value is true or false , 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 function returns the set of elements that are returned false by the filter function.

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

var arr=$.grep([0,1,2,3,4,5,6],function(n,i){ 
return n>2}
);
Copy after login

The above example returns [3,4,5,6], but we The value given to invert is true, for example

var arr=$.grep([0,1,2,3,4,5,6],function(n,i){
 return n>2
},ture);
Copy after login

, so what is returned now is [0,1,2], which is the element filtered out by the callback function.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How jquery traverses an array

Detailed explanation of the steps for jQuery ajax to call WCF service

The above is the detailed content of The grep() method implements array filtering. For more information, please follow other related articles on the PHP Chinese website!

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