English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
What is jQuery.grep()?
jQuery.grep() is a function that finds array elements that meet the filter function. The original array is not affected, and the return value is an array.
Usage Description:
Syntax:
jQuery.grep(array, function(elementOfArray, indexInArray) [, invert])
Parameter Description:
array
Type: Array
Array used to query elements.
function(elementOfArray, indexInArray)
Type: Function()
This function is used to handle the comparison of each element. The first parameter is the element of the array being checked, and the second parameter is the index value of the element. The function should return a boolean value. 'this' will be the global window object.
elementOfArray--Array Element
indexInArray--Element Index
invert
Type: Boolean
If 'invert' is false, or not provided, the function returns an array of all elements for which 'callback' returns true. If 'invert' is true, the function returns an array of all elements for which 'callback' returns false.
Example: Filter out elements in the original array that are not 5and the index value is greater than 4 elements. Then filter out all values that are 9 elements
<!DOCTYPE html> <html> <head> <style> div { color:blue; } p { color:green; margin:0; } span { color:red; } </style> <script src="http://cdn.bootcss.com/jquery/1.11.2/jquery.min.js></script> </head> <body> <div></div> <p></p> <span></span> <script> var arr = [ 1, 9, 3, 8, 6, 1, 5, 9, 4, 7, 3, 8, 6, 9, 1 ]); $("div").text(arr.join(", ")); arr = jQuery.grep(arr, function(n, i){ return (n != 5 && i > 4); }); $("p").text(arr.join(", ")); arr = jQuery.grep(arr, function (a) { return a != 9; }); $("span").text(arr.join(", ")); </script> </body> </html>
The result is:
1, 9, 3, 8, 6, 1, 5, 9, 4, 7, 3, 8, 6, 9, 1
1, 9, 4, 7, 3, 8, 6, 9, 1
1, 4, 7, 3, 8, 6, 1
Thank you for reading, I hope it can help everyone, thank you for your support to this site!