each() 方法规定为每个匹配元素规定运行的函数,返回 false 可用于及早停止循环。
$(selector).each(function(index,element))
map() 把每个元素通过函数传递到当前匹配集合中,生成包含返回值的新的 jQuery 对象。
$(selector).map(callback(index,domElement))
jquery中的each函数和map函数的用法看起来差不多,但其实还是有一点区别的。
其中一个重要的区别是,each返回的是原来的数组,并不会新创建一个数组。
而map方法会返回一个新的数组。如果在没有必要的情况下使用map,则有可能造成内存浪费。
例如:
var items = [1,2,3,4];
var newItems1 = $.each(items, function(i) {
return i + 1;
});
console.log(newItems1);
// newItems1 is [1,2,3,4]
var newItems2 = $.map(items, function(i) {
return i + 1;
});
console.log(newItems2)
// newItems2 is [2,3,4,5]