Answers:
该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) {});
return false;
1:回调函数的参数相反。
.each()
的,$.each()
's和.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!']
function shout() { alert(this + '!') } result = $.each(['lions', 'tigers', 'bears'], shout)
产生错误的结果会与您的答案相矛盾!!jsfiddle.net/9zy2pLev
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]
因此,“ 每个 ”函数返回原始数组,而“ 地图 ”函数返回新数组
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.
});