Internally jQuery call this for $("sel").each(function(){});
if ( isObj ) {
for ( name in object ) {
if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
break;
}
}
}
And the eq
is a simple slice:
eq: function( i ) {
return i === -1 ?
this.slice( i ) :
this.slice( i, +i + 1 );
}
So you can create a new each
function that instead of object[name]
will do a object:eq(i)
$("*").slice(1,2).toSource() == $("*").eq(1).toSource();
So to create your own each
:
$.fn.each2 = function(callback)
{
for ( var i = 0; i < this.length; ++i ) {
callback.call( this.eq(i), i, this.eq(i) )
}
};
$("*").each2(function(i, obj) {
alert(obj); // now obj is a jQuery object
});
It seems that each3
is faster than each2
http://www.jsfiddle.net/m7pKk/2/
$.fn.each2 = function(callback)
{
for ( var i = 0; i < this.length; ++i ) {
var jObj = this.eq(i);
callback.call( jObj, i, jObj )
}
};
$.fn.each3 = function(callback)
{
for ( var i = 0; i < this.length; ++i ) {
var jObj = $(this[i]);
callback.call( jObj, i, jObj )
}
};
See this example on jsFiddle with performance measurement.