返回值:ArrayjQuery.map(array, callback(elementOfArray, indexInArray))

Translate all items in an array or array-like object to another array of items.

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:

  • the translated value, which will be mapped to the resulting array
  • null, to remove the item
  • an array of values, which will be flattened into the full array

Map can iterate through Array-like objects, like a jQuery object, that have a length property.

示例:

A couple examples of using .map()

<!DOCTYPE html>
<html>
<head>
<style>
  div { color:blue; }
  p { color:green; margin:0; }
  span { color:red; }
  </style>
<script src="jquery.min.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>
演示:

示例:

Maps the original array to a new one and adds 4 to each value.

jQuery 代码:
$.map( [0,1,2], function(n){
   return n + 4;
 });
结果:
[4, 5, 6] 

示例:

Maps the original array to a new one and adds 1 to each value if it is bigger then zero, otherwise it's removed.

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

示例:

Maps the original array to a new one, each element is added with it's original value and the value plus one.

jQuery 代码:
$.map( [0,1,2], function(n){
   return [ n, n + 1 ];
 });
结果:
[0, 1, 1, 2, 2, 3] 

示例:

Maps the original array to a new one, each element is squared.

jQuery 代码:
$.map( [0,1,2,3], function (a) { return a * a; } );
结果:
[0, 1, 4, 9] 

示例:

Remove items by returning null from the function. This removes any numbers less than 50, and the rest are decreased by 45.

jQuery 代码:
$.map( [0, 1, 52, 97], function (a) { return (a > 50 ? a - 45 : null); } );
结果:
[7, 52] 

示例:

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

jQuery 代码:
var array = [0, 1, 52, 97];
array = $.map(array, function(a, index) {
  return [a - 45, index];
}); 
结果:
[-45, 0, -44, 1, 7, 2, 52, 3]