首页 > web前端 > js教程 > 正文

jQuery中关于.map使用详解

黄舟
发布: 2017-07-19 16:23:54
原创
1110 人浏览过

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
登录后复制
登录后复制
登录后复制
登录后复制

 

以上是jQuery中关于.map使用详解的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!