[英]jQuery map vs. each
在jQuery中, map
和each
函数似乎都做同样的事情。 两者之间是否存在实际差异? 你什么时候选择使用一个而不是另一个?
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) {});
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!']
的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]
。
我明白这个 :
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]
所以,“ each ”函数返回原始数组,而“ map ”函数返回一个新数组
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.
});
当你在数组上工作时,Jquery.map更有意义,因为它对数组表现很好。
在迭代选择器项时最好使用Jquery.each。 这证明了map函数不使用选择器。
$(selector).each(...)
$.map(arr....)
如您所见,map不适用于选择器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.