Example of $. each () function usage in jQuery, jquery. each
Syntax:
$.each( collection, callback(indexInArray, valueOfElement) )
It is worth mentioning that forEach can easily traverse arrays and NodeList. The jQuery object in jQuery has already deployed such traversal methods, while the forEach method can be used in native JavaScript, but IE does not support it. Therefore, we can manually 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 <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 ';});
The $. each () function in jQuery is more powerful. The $. each () function is different from the $ (selector). each () function. $. The each () function can be used to traverse any set, whether it is a JavaScript object or an array. If it is an array, each time the callback function passes the subscript of an array and the value of the array corresponding to this subscript (this value can also be obtained through the this keyword in the function body, however, JavaScript usually treats this value as an object. Even if it is just a simple string or a number, this function returns the traversed object, which is the first parameter of this function, note that here is the original array, which is different from map.
Collection indicates the target array, callback indicates the callback function (defined by yourself), the first parameter of the callback function is the subscript of the array, and the second parameter is the element of the array. Of course, we can also set only one parameter for the callback function. This parameter must be a subscript, and no parameter is acceptable.
Example 1:Input Array
<!DOCTYPE html>
Output:
0: 52 1: 97
Example 2:If a ing is used as a set, the callback function imports a key-value pair each time.
<!DOCTYPE html>
Output:
flammable: inflammable duh: no duh
Example 3:You can exit $. each () when return false in the callback function. If a non-false value is returned, it will immediately go to the next traversal, just like using continue in the for loop.
<! DOCTYPE html>
Output:
Mine is one. – 1 Mine is two. – 2 Mine is three. – 3 - 4 - 5