jQuery源码 —each方法
each: function( object, callback, args ) {var name, i = 0,length = object.length,// 这样判断是否为Object还挺奇怪的,下面的代码根据{key:value}和[]两种类型进行遍历// 一般来说,Element和{}对象的length属性是undefinedisObj = length === undefined || jQuery.isFunction( object );if ( args ) {if ( isObj ) {for ( name in object ) {if ( callback.apply( object[ name ], args ) === false ) {break;}}} else {for ( ; i < length; ) {if ( callback.apply( object[ i++ ], args ) === false ) {break;}}}// A special, fast, case for the most common use of each} else {if ( isObj ) {for ( name in object ) {// 如果回调函数return false;就中断遍历if ( callback.call( object[ name ], name, object[ name ] ) === false ) {break;}}} else {for ( ; i < length; ) {if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) {break;}}}}return object;}
/** * args有无值,回调函数的参数不同 * args有值时:(当前项,args) * args无值时:(object,name, 当前值) * */function each( object, callback, args ) {var name; //遍历时引用对象的keyif( args ){for( name in object ) {if( object.hasOwnProperty( name )) {if( callback.apply( object[name], args ) === false ) {break;}}}} else {for( name in object ) {if( object.hasOwnProperty( name )) {if( callback.call( object, name, object[name]) === false ) {break;}}}}// 返回处理后的objectreturn object;}