You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

41 lines
1.3 KiB

4 years ago
  1. var arrayEach = require('./_arrayEach'),
  2. baseEach = require('./_baseEach'),
  3. castFunction = require('./_castFunction'),
  4. isArray = require('./isArray');
  5. /**
  6. * Iterates over elements of `collection` and invokes `iteratee` for each element.
  7. * The iteratee is invoked with three arguments: (value, index|key, collection).
  8. * Iteratee functions may exit iteration early by explicitly returning `false`.
  9. *
  10. * **Note:** As with other "Collections" methods, objects with a "length"
  11. * property are iterated like arrays. To avoid this behavior use `_.forIn`
  12. * or `_.forOwn` for object iteration.
  13. *
  14. * @static
  15. * @memberOf _
  16. * @since 0.1.0
  17. * @alias each
  18. * @category Collection
  19. * @param {Array|Object} collection The collection to iterate over.
  20. * @param {Function} [iteratee=_.identity] The function invoked per iteration.
  21. * @returns {Array|Object} Returns `collection`.
  22. * @see _.forEachRight
  23. * @example
  24. *
  25. * _.forEach([1, 2], function(value) {
  26. * console.log(value);
  27. * });
  28. * // => Logs `1` then `2`.
  29. *
  30. * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
  31. * console.log(key);
  32. * });
  33. * // => Logs 'a' then 'b' (iteration order is not guaranteed).
  34. */
  35. function forEach(collection, iteratee) {
  36. var func = isArray(collection) ? arrayEach : baseEach;
  37. return func(collection, castFunction(iteratee));
  38. }
  39. module.exports = forEach;