UNPKG

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