Skip to content

reduce

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

collection 减小为一个值,该值是运行 collectioniteratee 中每个元素的累积结果,其中每次连续调用都会提供前一次调用的返回值。如果未提供 accumulator,则使用 collection 的第一个元素作为初始值。迭代器使用四个参数调用:(accumulator, value, index|key, collection)。

¥Reduces collection to a value which is the accumulated result of running each element in collection thru iteratee, where each successive invocation is supplied the return value of the previous. If accumulator is not given, the first element of collection is used as the initial value. The iteratee is invoked with four arguments: (accumulator, value, index|key, collection).

许多 lodash 方法被保护起来,作为 _.reduce_.reduceRight_.transform 等方法的迭代器。

¥Many lodash methods are guarded to work as iteratees for methods like _.reduce, _.reduceRight, and _.transform.

初始值。assigndefaultsdefaultsDeepincludesmergeorderBysortBy

¥The guarded methods are: assign, defaults, defaultsDeep, includes, merge, orderBy, and sortBy

新增于

¥Since

0.1.0

参数

¥Arguments

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

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

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

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

  3. [accumulator] (*):的逆;

    ¥[accumulator] ()*: The initial value.

返回

¥Returns

(*):返回累积值。

¥()*: Returns the accumulated value.

示例

¥Example

js
_.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)

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