Array.prototype.reduce()在一个元素的数组上 [英] Array.prototype.reduce() on arrays of one element
问题描述
在以下 reduction + map
操作中,没有。 3令我困惑。任何人都可以解释原因
In following reduction + map
operations, no. 3 is puzzling me. Can anyone please explain why
// 1
[1,2,3,4,5].filter(x => x==3).reduce((x, y) => y) // -> 3, all good
// 2
[1,2,3,4,5].filter(x => x<=3).reduce((x, y) => 0) // -> 0, still good
// 3
[1,2,3,4,5].filter(x => x==3).reduce((x, y) => 0) // -> 3, hello?
换句话说:如何减少一个元素的数组忽略地图 0
操作?这将最终用于对象数组,如 .reduce((x,y)=> y.attr)
,它也返回 y
而不是单个元素数组的 y.attr
。
In other words: how come the reduction on the array of one element ignores the map to 0
operation? This would ultimately be used on an array of objects, as in .reduce((x,y) => y.attr)
which also returns y
instead of y.attr
for single element arrays.
推荐答案
过滤后的数组只包含一个元素,因此reduce将返回该值。
The filtered array contains only one element so reduce will return that value.
阅读文档:
如果数组只有一个元素(无论位置如何)并且没有提供initialValue,或者如果提供了initialValue但是数组为空,则返回solo值而不调用回调。
If the array has only one element (regardless of position) and no initialValue was provided, or if initialValue is provided but the array is empty, the solo value would be returned without calling callback.
更多信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
这篇关于Array.prototype.reduce()在一个元素的数组上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!