简体   繁体   English

一个元素的数组上的Array.prototype.reduce()

[英]Array.prototype.reduce() on arrays of one element

In following reduction + map operations, no. 在下面的reduction + map操作中,没有。 3 is puzzling me. 3让我感到困惑。 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?

In other words: how come the reduction on the array of one element ignores the map to 0 operation? 换句话说:一个元素数组的约简为什么会忽略映射为0操作? 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((x,y) => y.attr) ,对于单个元素数组,它也返回y而不是y.attr

The filtered array contains only one element so reduce will return that value. 过滤后的数组仅包含一个元素,因此reduce将返回该值。

Read the docs : 阅读文档:

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. 如果数组只有一个元素(无论位置如何)且未提供initialValue,或者如果提供了initialValue但数组为空,则将返回单独值而不调用回调。

For more : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce 有关更多信息: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM