SoFunction
Updated on 2025-02-28

Jquery uses each function to implement traversal and array processing

Each() method can make the DOM loop structure concise and not make mistakes easily. Each() function encapsulates a very powerful traversal function and is also very convenient to use. It can traverse one-dimensional arrays, multi-dimensional arrays, DOM, JSON, etc.

Using $each during JavaScript development can greatly reduce our workload.

Let me mention several common usages of each

Each handles one-dimensional array

 var arr = [['a', 'aa', 'aaa'], ['b', 'bb', 'bbb'], ['c', 'cc', 'ccc']]   
 $.each(arr, function(i, item){   
   $.each(item,function(j,val){
     alert(j);
    alert(val);
   }); 
});  

alert(i) will output 0, 1, 2

alert(val) will output aaa, bbb, ccc

Each process two-dimensional array

var arr2 = [['a', 'aa', 'aaa'], ['b', 'bb', 'bbb'], ['c', 'cc', 'ccc']] 
$.each(arr, function(i, item){ 
alert(i); 
alert(item); 
}); 

arr2 is a two-dimensional array, and item is equivalent to taking each array in this two-dimensional array.

item[0] relative to taking the first value in each one-dimensional array

alert(i) will output as 0, 1, 2, because this two-dimensional array contains 3 array elements

alert(item) will output as ['a', 'aa', 'aaa'], ['b', 'bb', 'bbb'], ['c', 'cc', 'ccc']

After a slight change in the processing of this two-digit array

var arr = [['a', 'aa', 'aaa'], ['b', 'bb', 'bbb'], ['c', 'cc', 'ccc']] 
$.each(arr, function(i, item){ 
$.each(item,function(j,val){
 alert(j);
alert(val);
 }); 
}); 

alert(j) will output as 0, 1, 2, 0, 1, 2, 0, 1, 2
alert(val) will output as a, aa, aaa, b, bb, bbb, c, cc, ccc

Each process json data, and this each is even more powerful, and can cycle every attribute

 var obj = { one:1, two:2, three:3};   
 each(obj, function(key, val) {   
   alert(key);  
   alert(val);   
 });  

Here alert(key) will output one two three

alert(val) will output one, 1, two, 2, three, 3

Why is the key not a number but an attribute? Because there is a set of unordered attribute-values ​​in the json format. Since it is unordered, how can there be numbers?
And this val is equivalent to obj[key]

ecah handles the dom element, here is an input form element as an example.

If you have a code like this in the dom

<input name="aaa" type="hidden" value="111" />
<input name="bbb" type="hidden" value="222" />
<input name="ccc" type="hidden" value="333" />
<input name="ddd" type="hidden" value="444"/>

Then you use each as follows

 $.each($("input:hidden"), function(i,val){ 
   alert(val);
   alert(i);
   alert();
   alert();  
 }); 

Then, alert(val) will output [object HTMLInputElement] because it is a form element.
alert(i) will output as 0, 1, 2, 3

alert(); will output aaa,bbb,ccc,ddd, if used, the same result will be output
alert(); will output 111,222,333,444, if used will output the same result

If the above code is changed to the following form

$("input:hidden").each(function(i,val){
  alert(i);
  alert();
  alert();    
});

As you can see, the output results are the same, and I don’t know what the difference between the two writing methods is. This change will also output the same result when applied to the above sections of the array.

In this way, the actual results of several examples have been answered. Then continue to study it, but I can't know why it is.

From the above example, we can see that both jQuery and jQuery objects implement this method. For jQuery objects, the each method is simply delegated: the jQuery object is passed as the first parameter to the each method of jQuery.

Take a look at each implementation in jQuery (network excerpt)

function (object, callback, args) {
//This method has three parameters: object obj for operation, function fn for operation, and function parameter args for operation:  var name, i = 0,length = ;
  if (args) {
    if (length == undefined) {
      for (name in object) {
        if ((object[name], args) === false) {
          break;
        }
      }
    } else {
      for (; i &lt; length;) {
        if ((object[i++], args) === false) {
          break;
        }
      }
    }
  } else {
    if (length == undefined) {
      for (name in object) {
        if ((object[name], name, object[name]) === false) {
          break;
        }
      }
    } else {
      for (var value = object[0]; i &lt; length &amp;&amp; (value, i, value) !== false; value = object[++i]) {}
      /*object[0] gets the first DOM element in the jQuery object, and passes a for loop,
       Get to traverse each DOM element corresponding to the entire jQuery object, pass ( value, i, value);
       Point this object of callback to the value object, and pass two parameters, i represents the index value, and value represents the DOM element;
       where callback is a method similar to function(index, elem) { ... }.
       So you get $("...").each(function(index, elem){ ... });
       */
    }
  }
  return object;
}

jquery will automatically judge based on the passed elements, and then take the apply or call method based on the judgment result. In the implementation of fn, this pointer can be used to refer to the array or child elements of the object.

Objects are arrays

Each method will call the fn function one by one of the child elements in the array until the result returned by calling a child element is false. That is to say, we can process the fn function provided to make it exit each method call after it meets certain conditions. When each method provides arg parameter, the parameter passed by the fn function call is arg, otherwise it is: child element index, child element itself

Objects are not arrays

The biggest difference between this method and 1 is that the fn method will be carried out successively without considering the return value. In other words, all properties of the obj object are called by the fn method, even if the fn function returns false. The parameters passed in the call are similar to 1.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.