Skip to content

transform

js
_.transform(object, [iteratee=_.identity], [accumulator])

_.reduce 的替代方案;此方法将 object 转换为新的 accumulator 对象,该对象是运行其每个可枚举字符串键控属性至 iteratee 的结果,每次调用都可能改变 accumulator 对象。如果未提供 accumulator,则将使用具有相同 [[Prototype]] 的新对象。迭代器使用四个参数调用:(accumulator, value, key, object)。迭代函数可以通过显式返回 false 提前退出迭代。

¥An alternative to _.reduce; this method transforms object to a new accumulator object which is the result of running each of its own enumerable string keyed properties thru iteratee, with each invocation potentially mutating the accumulator object. If accumulator is not provided, a new object with the same [[Prototype]] will be used. The iteratee is invoked with four arguments: (accumulator, value, key, object). Iteratee functions may exit iteration early by explicitly returning false.

新增于

¥Since

1.3.0

参数

¥Arguments

  1. object (对象):要迭代的对象。

    ¥object (Object): The object to iterate over.

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

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

  3. [accumulator] (*):自定义累加器值。

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

返回

¥Returns

(*):返回累积值。

¥()*: Returns the accumulated value.

示例

¥Example

js
_.transform([2, 3, 4], function(result, n) {
  result.push(n *= n);
  return n % 2 == 0;
}, []);
// => [4, 9]

_.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
  (result[value] || (result[value] = [])).push(key);
}, {});
// => { '1': ['a', 'c'], '2': ['b'] }

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