> For the complete documentation index, see [llms.txt](https://lodash.shujuwajue.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lodash.shujuwajue.com/collection/foreach.md).

# \_.forEach（遍历数组或对象）

**语法：**

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

**源代码链接：**[source](https://github.com/lodash/lodash/blob/4.17.10/lodash.js#L9340)

**npm包链接：**[npm package](https://www.npmjs.com/package/lodash.foreach)

**描述：**

调用`iteratee`遍历`collection`(集合) 中的每个元素， iteratee 调用3个参数：*(value, index|key, collection)*。 如果迭代函数（iteratee）显式的返回`false`，迭代会提前退出。

> **注意:**&#x4E0E;其他"集合"方法一样，类似于数组，对象的 "length" 属性也会被遍历。想避免这种情况，可以用[`_.forIn`](https://lodash.com/docs/4.17.10#forIn)或者[`_.forOwn`](https://lodash.com/docs/4.17.10#forOwn)代替。

**开始版本：**&#x30;.1.0

**别名：***\\*.each\_

**参数：**

* `collection (Array|Object)`: 一个用来迭代的集合。
* `[iteratee=_.identity] (Function)`: 每次迭代调用的函数。

**返回值：**

* `(*)`: 返回集合 collection。

**例子：**

```javascript
_.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).
```
