Home  >  Article  >  Web Front-end  >  Detailed explanation on the use of .map in jQuery

Detailed explanation on the use of .map in jQuery

黄舟
黄舟Original
2017-07-19 16:23:541111browse

jQuery.map使用方法

jQuery.map(array,callback)
将一个数组中的元素转换到另一个数组中。
作为参数的转换函数会为每个数组元素调用,而且会给这个转换函数传递一个表示被转换的元素作为参数。转换函数可以返回转换后的值、null(删除数组中的项目)或一个包含值的数组,并扩展至原始数组中。

--------------------------------------------------------------------------------

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.

返回值
Array

参数
array (Array) : 待转换数组。

callback (Function) : 为每个数组元素调用,而且会给这个转换函数传递一个表示被转换的元素作为参数。函数可返回任何值。另外,此函数可设置为一个字符串,当设置为字符串时,将视为“lambda-form”(缩写形式?),其中 a 代表数组元素。如“a * a”代表“function(a){ return a * a; }”。

示例
将原数组中每个元素加 4 转换为一个新数组。

jQuery 代码:

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

结果:

[4, 5, 6]

--------------------------------------------------------------------------------

原数组中大于 0 的元素加 1 ,否则删除。

jQuery 代码:

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

结果:

[2, 3]

--------------------------------------------------------------------------------

原数组中每个元素扩展为一个包含其本身和其值加 1 的数组,并转换为一个新数组。

jQuery 代码:

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

结果:

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


过滤数组中小于 0 的元素。

HTML 代码:

<p>First</p><p>Second</p><p>Third</p><p>Fourth</p>


jQuery 代码:

var arr = jQuery.makeArray(document.getElementsByTagName_r("p"));
arr.reverse(); // 使用数组翻转函数

结果:

Fourth
Third
Second
First

过滤数组中小于 0 的元素。

HTML 代码:

<p>First</p><p>Second</p><p>Third</p><p>Fourth</p>


jQuery 代码:

var arr = jQuery.makeArray(document.getElementsByTagName_r("p"));
arr.reverse(); // 使用数组翻转函数

结果:

Fourth
Third
Second
First

过滤数组中小于 0 的元素。

HTML 代码:

<p>First</p><p>Second</p><p>Third</p><p>Fourth</p>


jQuery 代码:

var arr = jQuery.makeArray(document.getElementsByTagName_r("p"));
arr.reverse(); // 使用数组翻转函数

结果:

Fourth
Third
Second
First

附:过滤数组中小于 0 的元素。

HTML 代码:

<p>First</p><p>Second</p><p>Third</p><p>Fourth</p>


jQuery 代码:

var arr = jQuery.makeArray(document.getElementsByTagName_r("p"));
arr.reverse(); // 使用数组翻转函数

结果:

Fourth
Third
Second
First

 

The above is the detailed content of Detailed explanation on the use of .map in jQuery. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn