yisainan / web-interview

我是齐丶先丶森,收集整理全网面试题及面试技巧,旨在帮助前端工程师们找到一份好工作!更多详见公众号「前端面试秘籍」
MIT License
2.61k stars 507 forks source link

[选择题] 43.(单选题)下面代码的输出是什么 #1021

Open qiilee opened 4 years ago

qiilee commented 4 years ago
[1, 2, 3, 4].reduce((x, y) => console.log(x,y))
A:1 2 and 3 3 and 6 4 
B: 1 2 and 2 3 and 3 4
C: 1 undefined and 2 undefined and 3 undefined and 4 undefined
D: 1 2 and undefined 3 and undefined 4 

答案:D

解析:

reducer函数接收4个参数: • Accumulator (acc)(累计器) • Current Value (cur)(当前值) • Current Index (idx)(当前索引) • Source Array (src)(源数组)

reducer 函数的返回值将会分配给累计器,该返回值在数组的每个迭代中被记住,并最后成为最终的单个结果值。

reducer函数还有一个可选参数initialValue ,该参数将作为第一次调用回调函数时的第一个参数的值。如果没有提供initialValue ,则将使用数组中的第一个元素。 在上述例子,reduce方法接收的第一个参数(Accumulator)是 x,第二个参数(Current Value)是 y。 在第一次调用时,累加器x为1 , 当 前 值'y'为 2 , 打印出累加器和当前值:1和2。

例子中我们的回调函数没有返回任何值,只是打印累加器的值和当前值。如果函数没有返回值,则默认返回undefined。在下一次调用时,累加器为undefined ,当前值为'3',因此undefined和3被打印出。

在第四次调用时,回调函数依然没有返回值。累加器再次为 undefined ,当前值为“4”。undefined 和 4 被打印出