在以下约简操作中,不. 3让我感到困惑.谁能解释为什么
// 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.
解决方法:
过滤后的数组仅包含一个元素,因此reduce将返回该值.
阅读文档:
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