Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/427.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 一个元素的数组上的Array.prototype.reduce()_Javascript_Arrays_Reduction - Fatal编程技术网

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

Javascript 一个元素的数组上的Array.prototype.reduce(),javascript,arrays,reduction,Javascript,Arrays,Reduction,在下面的reduce+map操作中,第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).r

在下面的
reduce+map
操作中,第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?
//1
[1,2,3,4,5]。过滤器(x=>x==3)。减少((x,y=>y)/->3,都很好
// 2
[1,2,3,4,5]。过滤器(x=>x0)/->0,仍然良好
// 3
[1,2,3,4,5]。过滤器(x=>x==3)。减少((x,y)=>0)/->3,喂?

换句话说:为什么一个元素数组的缩减会忽略映射到
0
操作?这最终将用于对象数组,如
.reduce((x,y)=>y.attr)
中,它也返回
y
,而不是单个元素数组的
y.attr

过滤后的数组只包含一个元素,因此reduce将返回该值

阅读文档:

如果数组只有一个元素(无论位置如何)且未提供initialValue,或者如果提供了initialValue但数组为空,则将在不调用回调的情况下返回solo值


更多信息:

过滤后的数组只包含一个元素,因此reduce将返回该值

阅读文档:

如果数组只有一个元素(无论位置如何)且未提供initialValue,或者如果提供了initialValue但数组为空,则将在不调用回调的情况下返回solo值


更多信息:

规范只有一个元素部分:“如果数组只有一个元素(无论位置如何),并且没有提供initialValue,或者如果提供了initialValue,但数组为空,那么将在不调用回调的情况下返回solo值。”这显然会导致某种RTFM答案。非常感谢你叫我今天到此为止!规范中只有一个elementpart:“如果数组只有一个元素(无论位置如何),并且没有提供initialValue,或者如果提供了initialValue,但是数组为空,那么将在不调用回调的情况下返回solo值。”这显然会导致某种类型的RTFM回答。非常感谢你叫我今天到此为止!