在jQuery中,map
和each
函数似乎做同样的事情。两者之间是否存在实际差异?你什么时候选择使用一个而不是另一个?
答案 0 :(得分:260)
each
方法是一个不可变的迭代器,其中map
方法可以用作迭代器,但实际上是为了操作提供的数组并返回一个新的数组。 / p>
另一个需要注意的重要事项是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) {});
答案 1 :(得分:92)
1:回调函数的参数相反。
.each()
的,$.each()
和.map()
的回调函数首先获取索引,然后是元素
function (index, element)
$.map()
的回调具有相同的参数,但颠倒了
function (element, index)
2:.each()
,$.each()
和.map()
针对this
each()
以this
指向当前元素的方式调用函数。在大多数情况下,您甚至不需要回调函数中的两个参数。
function shout() { alert(this + '!') }
result = $.each(['lions', 'tigers', 'bears'], shout)
// result == ['lions', 'tigers', 'bears']
对于$.map()
,this
变量引用全局窗口对象。
3:map()
对回调的返回值做了一些特别的事
map()
在每个元素上调用该函数,并将结果存储在它返回的新数组中。您通常只需要使用回调函数中的第一个参数。
function shout(el) { return el + '!' }
result = $.map(['lions', 'tigers', 'bears'], shout)
// result == ['lions!', 'tigers!', 'bears!']
答案 2 :(得分:20)
each
函数遍历数组,每个元素调用一次提供的函数,并将this
设置为活动元素。这样:
function countdown() {
alert(this + "..");
}
$([5, 4, 3, 2, 1]).each(countdown);
将提醒5..
然后4..
然后3..
然后2..
然后1..
另一方面,Map接受一个数组,并返回一个新数组,其中每个元素都被该函数更改。这样:
function squared() {
return this * this;
}
var s = $([5, 4, 3, 2, 1]).map(squared);
会导致s为[25, 16, 9, 4, 1]
。
答案 3 :(得分:18)
我理解为:
function fun1() {
return this + 1;
}
function fun2(el) {
return el + 1;
}
var item = [5,4,3,2,1];
var newitem1 = $.each(item, fun1);
var newitem2 = $.map(item, fun2);
console.log(newitem1); // [5, 4, 3, 2, 1]
console.log(newitem2); // [6, 5, 4, 3, 2]
所以,“每个”函数返回原始数组,而“ map ”函数返回一个新数组
答案 4 :(得分:0)
var intArray = [1, 2, 3, 4, 5];
//lets use each function
$.each(intArray, function(index, element) {
if (element === 3) {
return false;
}
console.log(element); // prints only 1,2. Breaks the loop as soon as it encountered number 3
});
//lets use map function
$.map(intArray, function(element, index) {
if (element === 3) {
return false;
}
console.log(element); // prints only 1,2,4,5. skip the number 3.
});
答案 5 :(得分:-1)
当你在数组上工作时,Jquery.map更有意义,因为它对数组的表现非常好。
在迭代选择器项时最好使用Jquery.each。这证明了map函数不使用选择器。
$(selector).each(...)
$.map(arr....)
如您所见,map不适用于选择器。