Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

jQuery.map() method

jQuery.map() method

jQuery Miscellaneous MethodsjQuery Miscellaneous Methods

Example

Modify the values of an array using $.map()

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


Definition and Usage

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

**Note:** 1. Before jQuery 1.6, this function only supported iterating over arrays; starting from 1.6, it also supports iterating over objects.
2. map() also passes two arguments to the function: the first is the currently iterated element or property value, and the second is the array index or object property name of the current item.
3. The function's return value becomes an element in the result array; if the return value is null or undefined, it is not 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
Add 4 to each value in the original array and map the results into a new array.

Add 1 to values greater than 0 in the original array
Add 1 to values greater than 0 in the original array and map them into a new array.

Add 1 to the values of the original array
Map each value of the original array together with the value plus 1 into a newly generated array.

Multiply the values of the original array by 2
Multiply each value in the original object by 2 and map them into a newly generated array.

Keys in the object
Map the keys in the object into a newly generated array.

The square of the values in the original array
Map the square of each value in the original array as the return result into a newly generated array.

Removing Elements
Remove elements by returning null from the processing function: remove values less than 50, and decrease the values of the remaining elements by 45.

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


jQuery Miscellaneous MethodsjQuery Miscellaneous Methods