该
each方法原本是一个不可变的迭代器,该
map方法可以用作迭代器,但实际上是要操纵提供的数组并返回一个新数组。
另一个需要注意的重要事项是,该
each函数返回原始数组,而该
map函数返回一个新数组。如果您过度使用map函数的返回值,则可能会浪费大量内存。
例如:
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函数从数组中删除项目。例如:
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]您还将注意到,
this该
map函数未映射。您将必须在回调中提供第一个参数(例如,我们在
i上面使用的)。具有讽刺意味的是,每个方法中使用的回调参数与map函数中的回调参数相反,因此请小心。
map(arr, function(elem, index) {});// versus each(arr, function(index, elem) {});


