$.each supporting length prop
by jboesch26
HTML
<div>asihuao suah sdiuha oshu aoiad</div>
<div>asihuao suah sdiuha oshu aoiad</div>
<div>asihuao suah sdiuha oshu aoiad</div>
<div>asihuao suah sdiuha oshu aoiad</div>
<div>!!!!asihuao suah sdiuha oshu aoiad</div>
JavaScript
jQuery.newEach = function( object, callback, args ){
var name, i = 0, v,
length = object.length,
// The line below was the only lined I changed
isObj = !(object instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && object[ 0 ] && object[ length -1 ] ) || jQuery.isArray( object ) ) ) || 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 ) {
v = object[ name ];
if ( callback.call( v, name, v ) === false ) {
break;
}
}
} else {
for ( ; i < length; i++ ) {
v = object[ i ];
if ( callback.call( v, i, v ) === false ) {
break;
}
}
}
}
return object;
}
$('body').append('Open up your console to see results.');
console.log('----- OLD EACH --------');
$.each({ a: '1', b: '2', length: 5 }, function(){
console.log(arguments);
});
console.log('----- NEW EACH (OBJ WITH LENGTH PROP) --------');
$.newEach({ a: '1', b: '2', length: 5 }, function(){
console.log(arguments);
});
console.log('----- NEW EACH (ARGUMENTS ARRAY-LIKE) --------');
(function(){
$.newEach(arguments, function(){
console.log(arguments);
});
})('hi', 'bob',...