Home > Web Front-end > JS Tutorial > body text

Analysis of four questions about jQuery's .grep() function

黄舟
Release: 2017-07-19 09:12:51
Original
1057 people have browsed it

Question 1: What is the source code of jQuery.grep?

//grep函数,第三个参数表示是否根据fn的结果取反!
grep: function( elems, callback, invert ) {
var callbackInverse,
matches = [],
i = 0,
//保存数组个数
length = elems.length,
//对传入的第二个参数取反,true变成false,false变成true
//如果invert为false,即!inverse为true,那么直接把函数返回true的元素加入,所以期望callbackExpect的就是true
callbackExpect = !invert;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
//如果invert是false,表示不取反,那么如果fn返回true,就直接加入进去matches数组
//获取回调函数结果的返回值的取反的结果
callbackInverse = !callback( elems[ i ], i );
if ( callbackInverse !== callbackExpect ) {
matches.push( elems[ i ] );
}
}
return matches;
}
Copy after login

Question 2: What are the calling methods of jQuery.grep?

In the winnow function

   if ( qualifier.nodeType ) {
		return jQuery.grep( elements, function( elem ) {//没有第三个参数,表示获取执行函数后返回为true元素在结果数组中
			return ( elem === qualifier ) !== not;
		});

	}
Copy after login

In winnow There is also a call

return jQuery.grep( elements, function( elem ) {
		return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not;<span style="font-family: Arial, Helvetica, sans-serif;">//没有第三个参数,表示获取执行函数后返回为true元素在结果数组中</span>
	});
Copy after login

in the function or in the winnow method

	return jQuery.grep( elements, function( elem, i ) {
			/* jshint -W018 */
			return !!qualifier.call( elem, i, elem ) !== not;<span style="font-family: Arial, Helvetica, sans-serif;">//没有第三个参数,表示获取执行函数后返回为true元素在结果数组中</span>
		});
Copy after login

Call in jQuery.buildFragment

       jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
Copy after login

This method is used to set the defaultChecked attribute of all input elements It is the same as checked

// Used in buildFragment, fixes the defaultChecked property
var rcheckableType = (/^(?:checkbox|radio)$/i);
function fixDefaultChecked( elem ) {
	if ( rcheckableType.test( elem.type ) ) {
		elem.defaultChecked = elem.checked;//这里没有明确返回真或者假,所以他只是用来修改元素,而不再保存修改后的数组!
	}
}
Copy after login

Question 3: What is the function of jQuery.grep method?

If the third parameter is not passed in, it means that we want to return the result after calling the callback function is an element that is true, so the function of jQuery.grep is to filter. Only elements that meet specific conditions will appear in the result array! Remember: The return value of this function is an array!
We use the following example to analyze how to select elements whose id and class are both father

 <p class="father" id="father" style="background-color:red;height:400px;background-color:#ccc;">  
</p>  
 <p class="father" style="background-color:red;height:400px;background-color:#ccc;">  
</p>
Copy after login

JS part

     //对每一个元素进行筛选,只有符合条件的元素才会在结果数组中!
       var result=jQuery.grep($(".father"),function(elem,index)
	   {
	      return elem.id==="father";
		  //grep通过false,true来判断是否在结果集合中;map通过明确的return elem
		  //而each通过false,true决定是否退出循环
	   });
        console.log(result);//打印[p#father.father]
Copy after login

So grep determines the returned elements by whether the return value is true or false, all Elements that meet the conditions form a DOM collection!
The HTML part remains unchanged, we modify the JS part to:

     //对每一个元素进行筛选,只有符合条件的元素才会在结果数组中!
       var result=jQuery.grep($(".father"),function(elem,index)
	   {
	      return elem.id==="father";
		  //grep通过false,true来判断是否在结果集合中;map通过明确的return elem
		  //而each通过false,true决定是否退出循环
	   },true);
        console.log(result);//[p.father]
Copy after login

At this time, because the third parameter is true, it will be inverted internally, so it means We want elements with a value of false to appear in the result array, so the result array only contains the second p element.

In fact, the code in the source code can be modified as:

//下面的代码可以修改为:
 callbackResult = callback( elems[ i ], i );//调用函数的结果
if ( callbackResult === callbackExpect ) {//如果调用的结果和期望的结果一样,那么直接放进结果数组返回
matches.push( elems[ i ] );
}
Copy after login

Question 4: What are the context and parameters in jQuery.grep?

Answer: Because it is not clear Call or apply is called, so the context is determined by the running environment. The first parameter is the element, and the second parameter is the subscript (Only jQuery.each, and instance each, the first parameter of the map method is the subscript, and the second parameter is the element!)

Summary:

(1) The $.each method emphasizes traversal, that is, traversing all the elements and then executing a callback function. If return false, then stop subsequent calls; grep emphasizes It is to filter all elements according to a function, and let all elements execute a function to see if the return value meets the expected return value. If it meets the expected return value, it can be included in the result array. The third parameter indicates whether to negate, so grep emphasizes filtering. ;map emphasizes modification, that is, modifying all collections of elements. (map emphasizes modification, grep emphasizes filtering, and each emphasizes traversal)

(2) The callback function of each The parameters passed in are the subscript and the element, with the subscript in front and the element in the back. The parameters passed in by other grep or map methods are the element and subscript, with the element in front and the subscript in the back (except for instance map and each methods)!

The above is the detailed content of Analysis of four questions about jQuery's .grep() function. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!