Skip to content

Instantly share code, notes, and snippets.

@ianpgall
Last active December 20, 2015 21:59
Show Gist options
  • Save ianpgall/6201721 to your computer and use it in GitHub Desktop.
Save ianpgall/6201721 to your computer and use it in GitHub Desktop.
JavaScript function that iterates over an object (Object or Array)
var Each = (function () {
"use strict";
var O, toString, is, ret;
O = {};
toString = O.toString;
is = function (o, t) {
return (toString.call(o) === "[object " + t + "]");
};
ret = function (obj, callback) {
var result, curKey, curVal, len;
if (is(obj, "Object")) {
for (curKey in obj) {
curVal = obj[curKey];
result = callback.call(curVal, curKey, curVal);
if (result === false) {
break;
}
}
} else if (is(obj, "Array")) {
for (curKey = 0, len = obj.length; curKey < len; curKey++) {
curVal = obj[curKey];
result = callback.call(curVal, curKey, curVal);
if (result === false) {
break;
}
}
}
};
return ret;
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment