jQuery.map()Method

jQuery 杂项方法jQuery Miscellaneous Methods

Examples

Use $.map() to modify an array's values

<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>

Try it Yourself »

Definition and Usage

The $.map() function is used to process each element in an array (or each property of an object) with a specified function, and packages the processing results into a new array to return.

Note:1. Before jQuery 1.6, this function only supported traversing arrays; starting with 1.6, it also supports traversing objects.
2. map() also passes two parameters to the function: one is the element or property value of the current iteration, and the other is the array index or object property name of the current iteration item.
3. The return value of the function will be 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 )

Parameters Description
object Array/Object type - The specified array or object to be processed.
callback Function type - The specified processing function.


实例

More Examples

Add 4 to each value in the original array
After adding 4 to each value in the original array, map them to a new array.

Add 1 to values greater than 0 in the original array
After adding 1 to values greater than 0 in the original array, map them to a new array.

Add 1 to the original array's values
Map each value in the original array and the result after adding 1 to that value into the newly generated array.

Multiply the original array's values by 2
After multiplying each value in the original object by 2, map them to the newly generated array.

Keys in the object
Map the keys in the object to the newly generated array.

Square of the original array's values
Use the second power (square) of each value in the original array as the return result, mapped into the newly generated array.

Remove elements
Remove elements by returning null in the processing function; remove values less than 50, and reduce the values of the elements that were not removed by 45.

Add elements
Add elements to the final result array by returning an array in the processing function.


jQuery 杂项方法jQuery Miscellaneous Methods

Other Extensions