JQuery functions map of and each of introduction and similarities and differences analysis

  • 2020-03-30 04:17:05
  • OfStack

Method syntax: map()

The map (the callback)
The callback function is called for each element in the wrapper set and the return value is collected into an instance of the jQuery object.
parameter
The callback function, which is called for each element in the wrapper set.
For example, the following code collects the id values of all the div elements on the page into a javascript array:


var iDs = $("div").map(function(){
    return (this.id==undefined) ? null :this.id;
}).get();

Look again at the set of checkboxes contained in the form below:


<form method="post" action="">
<fieldset>
<div>
<label for="two">2</label>
<input type="checkbox" value="2" id="two" name="number[]">
</div>
<div>
<label for="four">4</label>
<input type="checkbox" value="4" id="four" name="number[]">
</div>
<div>
<label for="six">6</label>
<input type="checkbox" value="6" id="six" name="number[]">
</div>
<div>
<label for="eight">8</label>
<input type="text" value="8" id="eight" name="number[]">
</div>
</fieldset>
</form>

We can get a comma-separated check box ID:


$(':checkbox').map(function() {
return this.id;
}).get().join();

The result of this call is a string, "two,four,six".

In the callback function, this points to the current DOM element in each iteration.

Method syntax: each()

Each (iterator)
Iterate over all the elements in the matching set, calling the passed iteration function for each element
Iterator (function) callback function, called for each element in the matching set
The each() method can also be used to traverse javascript array objects or even individual objects, for example:


$([a,b,c,d]).each(function(){
    alert(this);
})

This statement calls the iteration function for each element of the array passed in $(), and the this in the function points to a separate array item.

Each time the callback function executes, the current number of loops is passed as an argument (counting from 0). More importantly, the callback function is triggered in the context where the current DOM element is the context. So the keyword this always points to this element.

Suppose you have a simple unordered list on your page.


<ul>
<li>foo</li>
<li>bar</li>
</ul>

You can select and iterate over these lists:


$( "li" ).each(function( index ) {
console.log( index + ": "" + $(this).text() );
});

Each item in the list is displayed in the following message:

0: foo
1: the bar
The difference between the two

The map() method is mainly used to iterate over arrays and objects, and each() is mainly used to iterate over jquery objects.

Each () returns the original array, not a new one.
The map() method returns a new array. If you use a map when you don't need it, you can waste memory.


Related articles: