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) {});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…