Home > Article > Web Front-end > Is there a map method in jquery?
There is a map method in jquery; this method is used to use the specified function to process each element in the array or each attribute of the object, and encapsulate the processing results as a new array and return it, the syntax is "$. map (array or object to be processed, specified processing function)" or "jquery object.map (specified processing function)".
The operating environment of this tutorial: windows10 system, jquery3.2.1 version, Dell G3 computer.
$.map() function is used to process each element in the array (or each attribute of the object) using the specified function and encapsulate the processing results Returned for the new array.
1. Before jQuery 1.6, this function only supported traversing arrays; starting from 1.6, this function also supports traversing objects.
2. map() will also pass in two parameters to the function: one is the element or attribute value of the current iteration, and the other is the array index or object attribute name of the current iteration item.
3. The return value of this function will be used as an element in the result array. If the return value is null or undefined, it will not be added to the result array.
Syntax
$.map( object, callback )
object Array/Object type specifies the array or object that needs to be processed.
callback Processing function specified by Function type
Two forms:
$.map(arr|obj,callback): Convert elements in an array to another array, callback: function(ele,i): ele is the currently processed element, i is the subscript of the currently processed element, and what is returned is a JavaScript native array
jquery object.map(callback ): Convert a set of elements into other arrays, returning a jquery array object. callback:function(i,ele): Note that the position is different from format one.
The example is as follows:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>123</title> <style> div { color:blue; } p { color:green; margin:0; } span { color:red; } </style> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> </head> <body> <div></div> <p></p> <span></span> <script> $(function () { var arr = [ "a", "b", "c", "d", "e" ]; $("div").text(arr.join(", ")); arr = $.map(arr, function(n, i){ return (n.toUpperCase() + i); }); $("p").text(arr.join(", ")); arr = $.map(arr, function (a) { return a + a; }); $("span").text(arr.join(", ")); }) </script> </body> </html>
Output result:
Related video tutorial recommendation: jQuery video tutorial
The above is the detailed content of Is there a map method in jquery?. For more information, please follow other related articles on the PHP Chinese website!