Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Created December 29, 2012 06:24
Show Gist options
  • Select an option

  • Save WebReflection/4404939 to your computer and use it in GitHub Desktop.

Select an option

Save WebReflection/4404939 to your computer and use it in GitHub Desktop.
an Array#forEach like function to loop over object enumerable properties as for/in does. If you don't need to support IE < 9 you probably don't need this function too ;)
this.forIn = function (){
var
propertyIsEnumerable = "propertyIsEnumerable",
toString = "toString",
OK = {toString:1}[propertyIsEnumerable](toString),
keys = OK || [
propertyIsEnumerable,
toString,
"hasOwnProperty",
"isPrototypeOf",
"valueOf",
"toLocaleString",
"constructor"
],
num = OK || function(obj, callback, self){
for (var
key,
i = keys.length;
i--;
(key = keys[i]) in obj &&
callback.call(
self,
obj[key],
key,
obj
)
);
}
;
return function forIn(obj, callback, self) {
for(var key in obj)
callback.call(
self,
obj[key],
key,
obj
)
;
OK || num(obj, callback, self);
};
}();
/* example
forIn({toString:123}, function(value, key, obj) {
alert(value === 123 && key === "toString");
});
//*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment