jQuery map vs. each作者该解法对吗?
2015-06-11 22:58
721 查看
In jQuery, the map
and each
functions seem to do the same thing. Are there any practical differences between the two? When would you choose to use one instead of the other?
The eachmethod is meant to be an immutable iterator, where as the mapmethod can be used as an iterator, but is really meant to manipulate the supplied array and return a new array. Another important thing to note is that the eachfunction returns the original array while the mapfunction returns a new array. If you overuse the return value of the map function you can potentially waste a lot of memory. For example: var items = [1,2,3,4]; $.each(items, function() { alert('this is ' + this); }); var newItems = $.map(items, function(i) { return i + 1; }); // newItems is [2,3,4,5] You can also use the map function to remove an item from an array. For example: var items = [0,1,2,3,4,5,6,7,8,9]; var itemsLessThanEqualFive = $.map(items, function(i) { // removes all items > 5 if (i > 5) return null; return i; }); // itemsLessThanEqualFive = [0,1,2,3,4,5] You'll also note that the thisis not mapped in the mapfunction. You will have to supply the first parameter in the callback (eg we used iabove). Ironically, the callback arguments used in the each method are the reverse of the callback arguments in the map function so be careful. map(arr, function(elem, index) {}); // versus each(arr, function(index, elem) {}); |
相关文章推荐
- Jquery ajax方法解析返回的json数据
- JQuery学习系列2--选择器
- jQuery jcrop插件截图使用方法
- Jquery pagination 简单应用
- jquery初步(二) 选择器
- jquery的$().each,$.each
- jqueryUI的拖动说明
- php+jquery+ajax+json简单小例子
- jQuery选择器全面总结
- jQuery时间验证和转换为标准格式的时间
- jquery sticky停靠在右下角的插件 ,jquery pushytip提示框显示插件
- JQuery中$.ajax()方法参数详解
- JQuery学习系列1
- jquery页面刷新和返回页面
- jQuery lazyload插件详解和问题解答
- 基于jQuery鼠标悬停上下滑动导航条
- jQuery i18n国际化
- jQuery操控DOM元素
- ie8下jquery改变PNG的opacity出现黑边
- jquery实现的流式布局