foreach.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. var hasOwn = Object.prototype.hasOwnProperty;
  2. var toString = Object.prototype.toString;
  3. var isFunction = function (fn) {
  4. var isFunc = (typeof fn === 'function' && !(fn instanceof RegExp)) || toString.call(fn) === '[object Function]';
  5. if (!isFunc && typeof window !== 'undefined') {
  6. isFunc = fn === window.setTimeout || fn === window.alert || fn === window.confirm || fn === window.prompt;
  7. }
  8. return isFunc;
  9. };
  10. module.exports = function forEach(obj, fn) {
  11. if (!isFunction(fn)) {
  12. throw new TypeError('iterator must be a function');
  13. }
  14. var i, k,
  15. isString = typeof obj === 'string',
  16. l = obj.length,
  17. context = arguments.length > 2 ? arguments[2] : null;
  18. if (l === +l) {
  19. for (i = 0; i < l; i++) {
  20. if (context === null) {
  21. fn(isString ? obj.charAt(i) : obj[i], i, obj);
  22. } else {
  23. fn.call(context, isString ? obj.charAt(i) : obj[i], i, obj);
  24. }
  25. }
  26. } else {
  27. for (k in obj) {
  28. if (hasOwn.call(obj, k)) {
  29. if (context === null) {
  30. fn(obj[k], k, obj);
  31. } else {
  32. fn.call(context, obj[k], k, obj);
  33. }
  34. }
  35. }
  36. }
  37. };