Grammar:
$.each (collection, Callback (Indexinarray, valueofelement))
It is worth mentioning that foreach can easily traverse arrays and nodelist, the jquery object in jquery itself has deployed this kind of traversal method, while in native JavaScript can use the ForEach method, but IE is not supported, so we can hand To deploy the ForEach method to arrays and nodelist:
if (! Array.prototype.forEach) {
Array.prototype.forEach = function (FN, scope) {
for (var i = 0, len = this.length; I &l T Len ++i) {
Fn.call (scope, this[i], I, this);
}
After deployment, IE can also use foreach
document.getelementsbytagname (' P '). foreach (function (e) {
e.classname = ' inner '; c13/>});
The $.each () function in jquery is more powerful. $.each () function and $ (selector). each () is not the same. The $.each () function can be used to traverse any set, whether it's a JavaScript object or an array, if it's an array, the callback function passes the subscript of an array and the value of the array corresponding to the subscript (this value can also be obtained by the This keyword in the function body). But JavaScript usually treats this value as an object, even if it's just a simple string or a number, and the function returns the object being traversed, the first argument to the function, and note that this is the original array, which is the difference from the map.
Where collection represents the target array, callback represents the callback function (its own definition), the parameter of the callback function is the index of the array, and the second is the element of the array. Of course, we can also give the callback function to set only one parameter, this parameter must be subscript, and there is no parameter is also possible.
Example 1: incoming array
Output:
Example 2: If a map is used as a collection, the callback function passes in a key-value pair at a time
Output:
Flammable:inflammable
duh:no duh
Example 3: you can exit $.each () when return false in the callback function, and returning a false is the same as using continue in the For loop, immediately entering the next traversal
Output:
Mine is one. –1
Mine is two.–2
Mine is three.–3
-4
-5