Fe-interview: Day24:选择正确的答案

Created on 22 Jun 2020  ·  5Comments  ·  Source: lgwebdream/FE-Interview

console.log([2,1,0].reduce(Math.pow));
console.log([].reduce(Math.pow));

/ *
A. 2 报错
B. 2 NaN
C. 1 报错
D. 1 NaN
*/

每日一题会在下午四点在交流群集中讨论,五点小程序中更新答案
欢迎大家在下方发表自己的优质见解
二维码加载失败可点击 小程序二维码

扫描下方二维码,收藏关注,及时获取答案以及详细解析,同时可解锁800+道前端面试题。

All 5 comments

答案
C

解析

  • arr.reduce(callback[, initialValue])

    • reduce接受两个参数, 一个回调, 一个初始值

    • 回调函数接受四个参数 previousValue, currentValue, currentIndex, array

    • 需要注意的是 If the array is empty and no initialValue was provided, TypeError would be thrown.

      所以第二个会报异常. 第一个表达式等价于 Math.pow(2, 1) => 2; Math.pow(2, 0) =>1

[2,1,0].reduce(Math.pow)
等价于
[2,1,0].reduce((accumulator, currentValue) => Math.pow(accumulator, currentValue), 0) ==> 输出结果为:1

答案
C

解析

  • arr.reduce(callback[, initialValue])

    • reduce接受两个参数, 一个回调, 一个初始值
    • 回调函数接受四个参数 previousValue, currentValue, currentIndex, array
    • 需要注意的是 If the array is empty and no initialValue was provided, TypeError would be thrown.
      所以第二个会报异常. 第一个表达式等价于 Math.pow(2, 1) => 2; Math.pow(2, 0) =>1

答案是A

[2,1,0].reduce(Math.pow)
等价于
[2,1,0].reduce((accumulator, currentValue) => {
console.log(accumulator, currentValue)
return Math.pow(accumulator, currentValue)
} , 0)
// 0, 2
// 0, 1
// 0, 0

Math(0, 2) ==> 0
Math(0, 1) ==> 0
Math(0, 0) ==> 1

输出结果为 1

  1. 查看MDN介绍: reduce地址
  2. reduce的第二个参数s说明:作为第一次调用 callback函数时的第一个参数的值。 如果没有提供初始值,则将使用数组中的第一个元素。 在没有初始值的空数组上调用 reduce 将报错。

[2,1,0].reduce(Math.pow) 等价于:

[2, 1, 0].reduce((accumulator, currentValue) => {
      console.log(accumulator, currentValue, Math.pow(accumulator, currentValue))
      return Math.pow(accumulator, currentValue)
 }, 2)

Math.pow(2, 2) ==> 4
Math.pow(4, 1) ==> 4
Math.pow(4, 0) ==> 1

输出结果为 1

Was this page helpful?
0 / 5 - 0 ratings