Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

javascript - jQuery map与每个(jQuery map vs. each)

In jQuery, the map and each functions seem to do the same thing.(在jQuery中, mapeach函数似乎都做同样的事情。)

Are there any practical differences between the two?(两者之间是否存在实际差异?) When would you choose to use one instead of the other?(你什么时候选择使用一个而不是另一个?)   ask by dthrasher translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.(each方法都是一个不可变的迭代器,因为map方法可以用作迭代器,但实际上是为了操作提供的数组并返回一个新数组。)

Another important thing to note is that the each function returns the original array while the map function returns a new array.(另一个需要注意的重要事项是, each函数返回原始数组,而map函数返回一个新数组。)

If you overuse the return value of the map function you can potentially waste a lot of memory.(如果过度使用map函数的返回值,则可能会浪费大量内存。)

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.(您还可以使用map函数从数组中删除项目。)

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.(您还会注意到, this不会映射到map功能中。)

You will have to supply the first parameter in the callback (eg we used i above).(您将必须在回调中提供第一个参数(例如,我们在上面使用过i )。) Ironically, the callback arguments used in the each method are the reverse of the callback arguments in the map function so be careful.(具有讽刺意味的是,每个方法中使用的回调参数与map函数中的回调参数相反,因此要小心。)
map(arr, function(elem, index) {});
// versus 
each(arr, function(index, elem) {});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...