jQuery map与每个 [英] jQuery map vs. each

查看:95
本文介绍了jQuery map与每个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在jQuery中, map 每个函数似乎做同样的事情。两者之间是否存在实际差异?你什么时候选择使用一个而不是另一个?

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?

推荐答案

每个 方法都是一个不可变的迭代器,其中 map 方法可以用作迭代器,但是真正意味着操纵提供的数组并返回一个新数组。

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.

另一个需要注意的重要事项是每个 函数返回原始数组,而 map 函数返回一个新数组。如果过度使用map函数的返回值,可能会浪费大量内存。

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.

例如:

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]

你也可以使用map函数从数组中删除项目。例如:

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]

您还会注意到未映射到 map 函数中。您将必须在回调中提供第一个参数(例如,我们使用上面的 i )。具有讽刺意味的是,每个方法中使用的回调参数与map函数中的回调参数相反,所以要小心。

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) {});

这篇关于jQuery map与每个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆