jQuery API 返回首页目录 | jQuery API 中英文对照版
$.map(array, fn)
$.map(array, fn)

把一个数组中的项目转换到另一个数组中。

作为参数的转换函数会被每个数组项目调用,而且会给这个转换函数传递一个表示要转换的项目的参数。 转换函数可以返回转换后的值、null(删除数组中的项目)或一个包含值的数组--表示对原始数组项目的扩展模式。

返回值:Array

参数:

  • array (Array): 要转换的数组
  • fn (Function): 处理数组项目的函数
 
示例:

把原始的数组映射到一个新数组中,并给新数组中的每个值都加上4。

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

结果:

[4, 5, 6]

示例:

把原始的数组映射到一个新数组中,如果新数组中的值大于0,就给这个值加上1;否则将这值删除。

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

结果:

[2, 3]

示例:

把原始的数组映射到一个新数组中,将新数组中的每一个元素都扩展为两个,其中一个是其原始值,另一个是加上1之后的值。

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

结果:

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

 
$.map( array, fn )

Translate all items in an array to another array of items.

The translation function that is provided to this method is called for each item in the array and is passed one argument: The item to be translated.

The function can then return the translated value, 'null' (to remove the item), or an array of values - which will be flattened into the full array.

Return value: Array
Parameters:

  • array (Array): The Array to translate.
  • fn (Function): The function to process each item against.
 

Example:

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

 $.map( [0,1,2], function(n){     return n + 4;   });  
Result:
 [4, 5, 6]  

Example:

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

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

Example:

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

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


相关链接
asp之家 | jQuery官方网站 | jQuery中文网 | 电子书作者网站 | 电子书作者blog