您的位置:首页 > Web前端 > JQuery

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
each
method is meant to be an immutable iterator, where as the
map
method 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
each
function returns the original array while the
map
function 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
this
is not mapped in the
map
function. You will have to supply the first parameter in the callback (eg we used
i
above). 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) {});


  

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: