Method syntax: map()
map(callback)
The callback function is called for each element in the wrapped set and the return value is collected into an instance of the jQuery object.
Parameters
callback (Function) A callback function that is called for each element in the wrapped set.
For example, the following code collects the id values of all div elements on the page into a javascript array:
Look at the set of checkboxes contained in the form below:
We can get a comma separated checkbox ID:
The result of this call is the string, "two,four,six".
In the callback function, this points to the current DOM element in each iteration.
Method syntax: each()
each(iterator)
Traverse all elements in the matching set and call 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 single objects, for example:
This statement will call the iteration function for each element of the array passed in $(), and this in the function points to the individual array item.
Each time the callback function is executed, the current loop count will be passed as a parameter (counting starts from 0). More importantly, the callback function is triggered in the context of the current DOM element. Therefore the keyword this always points to this element.
Suppose we have a simple unordered list like this on the page.
You can select and iterate over these lists:
Each item in the list will be displayed in the following message:
0: foo
1: bar
The difference between the two
The map() method is mainly used to traverse operating arrays and objects, and each() is mainly used to traverse jquery objects.
each() returns the original array and does not create a new array.
The map() method returns a new array. If map is used unnecessarily, memory may be wasted.