# \_.reduce（数组或对象迭代累加后的结果）

**语法：**

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

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

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

**描述：**

压缩`collection`（集合）为一个值，通过`iteratee`（迭代函数）遍历`collection`（集合）中的每个元素，每次返回的值会作为下一次迭代使用(注：作为`iteratee`（迭代函数）的第一个参数使用)。 如果没有提供`accumulator`，则`collection`（集合）中的第一个元素作为初始值。(愚人码头注：`accumulator`参数在第一次迭代的时候作为`iteratee`（迭代函数）第一个参数使用。) iteratee 调用4个参数：*(accumulator, value, index|key, collection)*.

lodash 中有许多方法是防止作为其他方法的迭代函数（注：即不能作为iteratee参数传递给其他方法），例如：[`_.reduce`](https://lodash.com/docs/4.17.10#reduce),[`_.reduceRight`](https://lodash.com/docs/4.17.10#reduceRight), 和[`_.transform`](https://lodash.com/docs/4.17.10#transform)。

受保护的方法有（注：即这些方法不能使用[`_.reduce`](https://lodash.com/docs/4.17.10#reduce),[`_.reduceRight`](https://lodash.com/docs/4.17.10#reduceRight), 和[`_.transform`](https://lodash.com/docs/4.17.10#transform)作为 iteratee 迭代函数参数）：

`assign`,`defaults`,`defaultsDeep`,`includes`,`merge`,`orderBy`, 和`sortBy。`

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

**参数：**

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

**返回值：**

* `(*)`: 返回累加后的值。

**例子：**

```javascript
_.reduce([1, 2], function(sum, n) {
  return sum + n;
}, 0);
// => 3

_.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
  (result[value] || (result[value] = [])).push(key);
  return result;
}, {});
// => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
```
