Last active
December 10, 2015 21:18
-
-
Save pazguille/4494583 to your computer and use it in GitHub Desktop.
$.each() vs for(){}
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var collection = ['a','b','c','d','e']; | |
// Vanilla JavaScript | |
var i = 0, | |
len = collection.length; | |
for (; i < len; i += 1) { | |
console.log(collection[i]); | |
} | |
// jQuery | |
$.each(collection, function (i, e) { | |
console.log(e); | |
}); | |
// But, when you use $.each(), jQuery executes this code | |
each: function( obj, callback, args ) { | |
var name, | |
i = 0, | |
length = obj.length, | |
isObj = length === undefined || jQuery.isFunction( obj ); | |
if ( args ) { | |
if ( isObj ) { | |
for ( name in obj ) { | |
if ( callback.apply( obj[ name ], args ) === false ) { | |
break; | |
} | |
} | |
} else { | |
for ( ; i < length; ) { | |
if ( callback.apply( obj[ i++ ], args ) === false ) { | |
break; | |
} | |
} | |
} | |
// A special, fast, case for the most common use of each | |
} else { | |
if ( isObj ) { | |
for ( name in obj ) { | |
if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) { | |
break; | |
} | |
} | |
} else { | |
for ( ; i < length; ) { | |
if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) { | |
break; | |
} | |
} | |
} | |
} | |
return obj; | |
}, |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment