在看jQuery源码,jQuery.each()写的非常精粹

each源码
$('#img').each(callback);
jquery的each方法是调用jquery.fn.each方法,$('img')是dom数组集合。

	each: function( callback, args ) {
		return jQuery.each( this, callback, args ); // this是选择器结果array
	}

有几个值得借鉴的写法:
1.数组和对象的区别,数组有length,对象肯定没有,再通过isFunction判断.
2.args是数组参数,apply和call区别调用
3.如果callback中返回false,则退出遍历操作
4.object支持array和{}

	each: function( object, callback, args ) {
		var name, i = 0,
			length = object.length,
			isObj = 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 ) {
					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;
	}

自己写个简易的each程序和测试如下:

var f = function(obj, callback){
  var name, i=0,
  length = obj.length;
  for(; i>" + i + "=" + a[i]);
  for(name in a[i])
    console.log(name + "=" + a[i][name])
})

你可能感兴趣的:(501框架,102JavaScript)