Jquery each和map 的区别
1,回调函数的参数顺序相反,each:i,elem,map:elem,i
2,返回值不同,map返回一个新的数组,each返回原始数组
回调的返回值,each只能返回 true 和 false,map返回的是新数组的元素
3,map 的回调函数里 ,没有 this,each中的this代表当前迭代对象
4,chrome 中 ,javascript是自带map方法的
var aaa = [11, 22, 33]; aaa.map(function (a, b) { console.log('a=' + a + ',b=' + b); return a * b; });
结果:
[0, 22, 66]
所以,chrome中的map与$.map是一致的,但是chrome的map看不到内部的实现
5,$("xxx").map和$.map是一样的,$("").map:
function ( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }
each 也是同样情况:$("").each:
function ( callback, args ) { return jQuery.each( this, callback, args ); }
总结:
在我看来,jquery的map方法,可以理解为 sql语句中的 where,或者linq中的where
而each仅仅是一个迭代器,相当于foreach,毕竟javascript是没有foreach的,这也许是补充吧
http://msdn.microsoft.com/zh-cn/express/ff679976(v=vs.90)
http://stackoverflow.com/questions/749084/jquery-map-vs-each