Skip to content

Instantly share code, notes, and snippets.

@rwaldron
Forked from 1Marc/fn arrEach and objEach
Created July 25, 2011 16:14
Show Gist options
  • Save rwaldron/1104485 to your computer and use it in GitHub Desktop.
Save rwaldron/1104485 to your computer and use it in GitHub Desktop.
"But $.each is slow!" ..use fn arrEach and objEach then!!
// arrEach and objEach plugins
// code under MIT license by Marc Grabanski http://marcgrabanski.com
// jsperf tests: http://jsperf.com/each-vs-fn-arreach-and-objeach
$.arrEach = function(arr, cb){
for (var i = 0, item; item = arr[i]; ++i) {
cb.apply(item, [i, item]);
}
return arr;
}
$.fn.arrEach = function(cb){
return $.arrEach(this, cb);
}
$.objEach = function(obj, cb){
for (var i in obj) {
cb.apply(obj[i], [i, obj[i]]);
}
return obj;
}
$.fn.objEach = function(cb){
return $.objEach(this, cb);
}
// EXAMPLES
// examples using array each
$.arrEach(["foo", "bar"], function(i, item){
console.log(i, item);
});
$(["foo", "bar"]).arrEach(function(i, item){
console.log(i, item);
});
// examples using object each
$.objEach({"foo":"bar", "baz":"bla"}, function(i, item){
console.log(i, item);
});
$({"foo":"bar", "baz":"bla"}).objEach(function(i, item){
console.log(i, item);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment