Примеры для jQuery.map()


Use $.map() to change the values of an array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.map demo</title>
<style>
div {
color: blue;
}
p {
color: green;
margin: 0;
}
span {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div></div>
<p></p>
<span></span>
<script>
var arr = [ "a", "b", "c", "d", "e" ];
$( "div" ).text( arr.join( ", " ) );
arr = jQuery.map( arr, function( n, i ) {
return ( n.toUpperCase() + i );
});
$( "p" ).text( arr.join( ", " ) );
arr = jQuery.map( arr, function( a ) {
return a + a;
});
$( "span" ).text( arr.join( ", " ) );
</script>
</body>
</html>

Демонстрация:

Map the original array to a new one and add 4 to each value.

1
2
3
$.map( [ 0, 1, 2 ], function( n ) {
return n + 4;
});

Result:

1
[4, 5, 6]

Map the original array to a new one, adding 1 to each value if it is bigger then zero and removing it if not.

1
2
3
$.map( [ 0, 1, 2 ], function( n ) {
return n > 0 ? n + 1 : null;
});

Result:

1
[ 2, 3 ]

Map the original array to a new one; each element is added with its original value and the value plus one.

1
2
3
$.map( [ 0, 1, 2 ], function( n ) {
return [ n, n + 1 ];
});

Result:

1
[ 0, 1, 1, 2, 2, 3 ]

Map the original object to a new array and double each value.

1
2
3
4
var dimensions = { width: 10, height: 15, length: 20 };
dimensions = $.map( dimensions, function( value, index ) {
return value * 2;
});

Result:

1
[ 20, 30, 40 ]

Map an object's keys to an array.

1
2
3
4
var dimensions = { width: 10, height: 15, length: 20 };
var keys = $.map( dimensions, function( value, key ) {
return key;
});

Result:

1
[ "width", "height", "length" ]

Map the original array to a new one; each element is squared.

1
2
3
$.map( [ 0, 1, 2, 3 ], function( a ) {
return a * a;
});

Result:

1
[ 0, 1, 4, 9 ]

Map the original array to a new one, removing numbers less than 50 by returning null and subtracting 45 from the rest.

1
2
3
$.map( [ 0, 1, 52, 97 ], function( a ) {
return (a > 50 ? a - 45 : null);
});

Result:

1
[ 7, 52 ]

Augment the resulting array by returning an array inside the function.

1
2
3
4
var array = [ 0, 1, 52, 97 ];
array = $.map( array, function( a, index ) {
return [ a - 45, index ];
});

Result:

1
[ -45, 0, -44, 1, 7, 2, 52, 3]