Description: Translate all items in an array or array-like object to another array of items.
arrayThe Array to translate.
callback(elementOfArray, indexInArray)The function to process each item against. The first argument to the function is the list item, the second argument is the index in array The function can return any value. this
will be the global window object.
The $.map() method applies a function to each item in an array, collecting the results into a new array.
The translation function that is provided to this method is called for each item in the array and is passed two arguments: The item to be translated, and the index within the array.
The function can return:
null
, to remove the itemMap can iterate through Array-like objects, like a jQuery object, that have a length property.
<!DOCTYPE html>
<html>
<head>
<style>
div { color:blue; }
p { color:green; margin:0; }
span { color:red; }
</style>
<script src="https://code.jquery.com/jquery-latest.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( [0,1,2], function(n){
return n + 4;
});
[4, 5, 6]
$.map( [0,1,2], function(n){
return n > 0 ? n + 1 : null;
});
[2, 3]
$.map( [0,1,2], function(n){
return [ n, n + 1 ];
});
[0, 1, 1, 2, 2, 3]
$.map( [0,1,2,3], function (a) { return a * a; } );
[0, 1, 4, 9]
$.map( [0, 1, 52, 97], function (a) { return (a > 50 ? a - 45 : null); } );
[7, 52]
var array = [0, 1, 52, 97];
array = $.map(array, function(a, index) {
return [a - 45, index];
});
[-45, 0, -44, 1, 7, 2, 52, 3]