search
HomeWeb Front-endJS TutorialDetailed explanation of the difference between Jquery's $(selector).each() and $.each()

We have all used the each function in Jqurey, and we all know that there are two ways to call each(), one is to call through $.each(), and the other is to call through $(selector).each() , so what’s the difference between them?

If you look at the Jquery source code, you will know that $.each() is the core implementation, $(selector).each() is the $.each() called, let’s first analyze $.each( ) source code (at the bottom):

The each (obj, callback, args) function receives 3 parameters: obj - the object or array to be traversed, callback - the callback function to be traversed and executed , args--the array specified by yourself (ignore it first).

The implementation of each method in jQuery uses the call method. The call method can set the context. First, in the following example, the effect of array each is the same. Why not call it directly?

You can change the pointer of this through call.

var testCall = function(obj, callback){
    callback.call(obj, 1);
}

testCall(["1. Change the pointer of this", "2. The function can be called internally through this"], function(index){ //Using the call method, you can directly access the call through this The object passed in as the first parameter.
alert(this[index]); //2. The function can be called through this });

Does not use the call method. this.

var test = function(obj, callback){
    callback(obj, 1);
}

test(["1. Change the pointer of this", "2. The function can be called through this inside the function"], function(index){ //Do not use call method, do not use this.
alert(this[index]); //undefined});

jQuery.each should be the this point modified by call;

$.each([1,2,3], function (index, item) {    console.log({index:index,value:item,_this:this});
});/*
  Object {index: 0, value: 1, _this: Number}
  Object {index: 1, value: 2, _this: Number}
  Object {index: 2, value: 3, _this: Number}
*/

I haven’t looked at the jQuery source code, use callback.call is a copycat and should be implemented in the same way.

var each = function(arr, callback){
  for( var index = 0 ; index < arr.length ; index++ ){
    callback.call(arr[index], index, arr[index]);
  }
}
each([1,2,3], function (index, item) {
    console.log({index:index,value:item,_this:this});
});/*
  Object {index: 0, value: 1, _this: Number}
  Object {index: 1, value: 2, _this: Number}
  Object {index: 2, value: 3, _this: Number}
*/

Note: this, if call is not used, this cannot be used in the callback function.

1. The case without args

Generally speaking, args are not commonly used, so we will not discuss the situation when if (args) is established first, that is, just look at the gray mark in the code part, this is also the core part of each() function

if(isArray) {
      for(; i < length; i++) {
        value = callback.call(obj[i], i, obj[i]);
        if(value === false) { break; }
      }
    }

If the object you want to traverse is an array type, enter this code block
 for loopTraverse Each element of the array , and then use the call method to execute obj[i].callback(i,obj[i]),
Therefore, when you write the callback function yourself, you should be aware that jquery will use arrays Each object in the callback method executes your callback function. The parameters passed are the index of the element in the array and the element. At the same time, this inside the callback method also points to the element;
The next line is to determine whether the callback function has returned a value. If the callback function returns false, break out of the array loop.

If the object you pass can also be traversed, the code is the same as the above array traversal

else {
      for(i in obj) {
          value = callback.call(obj[i], i, obj[i]);
          if(value === false) { break; }
        }
    }

If you pass the object, use for(x in y) to traverse Attributes of object ,
The principle is the same as above, except that it is replaced with the attribute x inside the object to execute the callback function, which is equivalent to obj.attr.callback(i,obj.attr);
Return If the function returns false, the loop operation will also end.

2. The situation with args

When calling each() with the third parameter, the following code block will be entered for analysis:  

if(isArray) {            
   for(; i < length; i++) {
     value = callback.apply(obj[i], args);                
     if(value === false) { break; }
            }
        } else {            
        for(i in obj) {
          value = callback.apply(obj[i], args);                
          if(value === false) { break; 
          }
        }
  }

In the same way, it will first determine whether the object you want to traverse is an array. If it is an array, traverse the element obj[i] of the array and execute obj[i].callback(args)
Note ! The parameter passed here is the args array you passed in. This is different from the args parameter without. That is to say, if you call the each function and pass in your own array parameter, the callbackParameters of the functionThe list is the args array you passed. Same as above for everything else.

$(selector).each(callback,args) function receives 2 parameters: callback--the callback function to be traversed and executed, args--the array specified by yourself. After understanding the $.each() function, $(selector).each is simple. Open the source code and find that the $.each() function is called inside $(selector).each. The source code is as follows:

each: function( callback, args ) {
      return jQuery.each( this, callback, args );
  },

You can see that when calling $.each(), the obj parameter is written as this, which is $(selector). This is the jquery selector returning a jqueryinternal object.  

Summary: The difference between $.each() and $(selector).each() is that the former can traverse all objects or arrays, while the latter is returned by the jquery selector jquery internal objects are traversed, the former is more powerful

The above is the detailed content of Detailed explanation of the difference between Jquery's $(selector).each() and $.each(). For more information, please follow other related articles on the PHP Chinese website!

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
JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool