reduce
的说明:
我能看出如何将_.reduce(collection, [iteratee=_.identity], [accumulator])
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).
Many lodash methods are guarded to work as iteratees for methods like _.reduce, _.reduceRight, and _.transform.
The guarded methods are: assign, defaults, defaultsDeep, includes, merge, orderBy, and sortBy
reduce
应用于大多数其他方法,因为它们大致遵循方法签名。例如,assign
和defaults
的形式为(非正式TypeScript伪代码):
_.assign and _.defaults: (object: object, sources: collection) => object
^ accumulator ^ value ^ same type as accumulator
同样,sortBy
也有意义:
_.sortBy: (collection: object, iteratees: sort_fn[]) => object
^ accumulator ^ value ^ same type as accumulator
我可以看到这些的有用用例,例如:
console.log('reduce',
_.reduce([{a: 2, b: 4}, [123, 52], {a: 5}], _.assign),
_.reduce([{a: 2, b: 4}, [123, 52], {a: 5}], _.defaults),
_.reduce([[e => e.a], [e => e.b]], _.sortBy,
[{a: 3, b: 2}, {a: 3, b: 3}, {a: 2, b: 15}, {a: -2, b: 3}])
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
然而,我不确定如何在使用 orderBy
和 includes
时应用此方法。也就是说,
_.orderBy: (collection: object, iteratees: sort_fn[], orders: ('asc' | 'desc')[]) => object
^ accumulator ^ value ^ index??? ^ same type as accumulator
查看源代码并跟随一些方法调用,似乎这仍然有效,尽管第三个参数是'asc' | 'desc'
值的数组(由于保护,它会特殊处理)。最终,通过保护,它似乎将所有order
默认为asc
,因此它的作用就像sortBy
。
console.log('reduce',
_.reduce([[e => e.a], [e => e.b]], _.orderBy,
[{a: 3, b: 2}, {a: 3, b: 3}, {a: 2, b: 15}, {a: -2, b: 3}])
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
sortBy
的替代品,有效地使orders
参数无用。
对于includes
,我甚至不确定如何将其用作reducer函数,因为它的返回类型(布尔值)与其第一个参数不同,例如:
_.includes: (collection: object, value: any) => boolean
^ accumulator ^ value ^ not same type as accumulator?
我的问题是:是否有任何实用的方法可以将_.orderBy
和_.includes
用作_.reduce
或_.transform
迭代器?如果不能,为什么lodash文档中列出了这样一种受保护的函数,可以以这种方式使用?
抱歉,如果这听起来有点像两个问题,但我认为它们足够相关,应该放在一起。
_.includes
- 你可以这样使用它:_.reduce([[1, 2, 3], 3], _.includes)
,它检查第一个索引是否包含第二个索引。所以,它类似于_.includes.apply(null, [[1, 2, 3], 3])
。然而,我无法想出为什么你会想这样调用它。 - VLAZ