Home  >  Article  >  Web Front-end  >  Detailed explanation of jQuery.grep() function

Detailed explanation of jQuery.grep() function

高洛峰
高洛峰Original
2016-12-13 14:57:541614browse

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

Detailed explanation of jQuery.grep() function

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


Statement:
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