iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 6
0
自我挑戰組

利用30分鐘~想一個前端問題系列 第 6

利用30分鐘~想一個前端問題 Day6-average

average

Returns the average of two or more numbers.

Use Array.prototype.reduce() to add each value to an accumulator, initialized with a value of 0, divide by the length of the array.

const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length;
EXAMPLES
average(...[1, 2, 3]); // 2
average(1, 2, 3); // 2

個人分析

其實就是使用reduce 的加總 再除以 陣列的長度得到總和。
大概就是要先搞清楚陣列的用法。### 個人分析

記憶點:

1.Array.prototype.reduce()

es6 的reduce()感覺就是個萬用方法, (讓數組中的前項和後項做某種計算,並累計最終值)

let arr = [1,2,3,4,5];

let result = arr.reduce((prev, cur, index, arr)=> {
    return prev + cur;
});

callbackFunction 包含4個參數,先解釋下它們的意思:

  • prev:第一項的值或者上一次疊加的結果值
  • cur: 當前會參與疊加的項
  • index: 當前索引
  • arr: 數組本身

如果想自定義初始值,那可以給reduce添加第二個參數(initialValue),如下

arr.reduce(callback(accumulator, currentValue, index, array), initialValue)

參考資料

Array.prototype.reduce()


上一篇
利用30分鐘~想一個前端問題 Day5-omit
下一篇
利用30分鐘~想一個前端問題 Day7--isValidJSON
系列文
利用30分鐘~想一個前端問題30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言