Analysis of four questions about jQuery's .grep() function
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; }
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; }); }
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> });
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> });
Call in jQuery.buildFragment
jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
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;//这里没有明确返回真或者假,所以他只是用来修改元素,而不再保存修改后的数组! } }
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>
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]
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]
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 ] ); }
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: <

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

jQuery is a popular JavaScript library widely used in web development. During web development, it is often necessary to dynamically add new rows to tables through JavaScript. This article will introduce how to use jQuery to add new rows to a table, and provide specific code examples. First, we need to introduce the jQuery library into the HTML page. The jQuery library can be introduced in the tag through the following code:
