Skip to content

forEach

js
_.forEach(collection, [iteratee=_.identity])

迭代 collection 的元素并为每个元素调用 iteratee。迭代器使用三个参数调用:(value, index|key, collection)。迭代函数可以通过显式返回 false 提前退出迭代。

¥Iterates over elements of collection and invokes iteratee for each element. The iteratee is invoked with three arguments: (value, index|key, collection). Iteratee functions may exit iteration early by explicitly returning false.

注意:与其他 "集合" 方法一样,具有 "length" 属性的对象像数组一样进行迭代。要避免此行为,请使用 _.forIn_.forOwn 进行对象迭代。

¥Note: As with other "Collections" methods, objects with a "length" property are iterated like arrays. To avoid this behavior use _.forIn or _.forOwn for object iteration.

新增于

¥Since

0.1.0

别名

¥Aliases

_.each

参数

¥Arguments

  1. collection (数组|对象):要迭代的集合。

    ¥collection (Array|Object): The collection to iterate over.

  2. [iteratee=_.identity] (函数):每次迭代调用的函数。

    ¥[iteratee=_.identity] (Function): The function invoked per iteration.

返回

¥Returns

(*):返回 collection

¥()*: Returns collection.

示例

¥Example

js
_.forEach([1, 2], function(value) {
  console.log(value);
});
// => Logs `1` then `2`.

_.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
  console.log(key);
});
// => Logs 'a' then 'b' (iteration order is not guaranteed).

Lodash v4.17 中文网 - 粤ICP备13048890号