更新时间:2023-10-30 23:18:34
jQuery 的每个源代码如下(感谢 John Resig 和 MIT License):
The source code for jQuery's each is as follows (Thank you John Resig and MIT License):
each: function( object, callback, args ) {
var name, i = 0, length = object.length;
if ( args ) {
if ( length === undefined ) {
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 ( length === undefined ) {
for ( name in object )
if ( callback.call( object[ name ], name, object[ name ] ) === false )
break;
} else
for ( var value = object[0];
i < length && callback.call( value, i, value ) !== false; value = object[++i] ){}
}
return object;
}
正如您所看到的,在大多数情况下,它使用基本的 for 循环,其中唯一的开销实际上只是回调本身.应该不会对性能产生影响.
As you can trace and see, in most cases it is using a basic for loop where the only overhead is really just the callback itself. Shouldn't make a difference in performance.
这是因为意识到选择器开销已经发生并且您得到了一个填充数组 object
.
This is with the realization that selector overhead has already occurred and you are given a populated array object
.