[JS] reduce的使用

張庭瑋
May 25, 2021

--

今天工作剛好碰到需要使用的地方,太少使用了,一碰到就原地炸開,來記錄一下解決的過程

先貼個MDN

今天碰到的問題是:我有個物件長這樣

list = { [key]: boolean } , 我要確認 list中所有值皆為 truereturn true , 否則 return false

簡單一點當然可以使用 forEach

let result = trueObject.keys(list).forEach(key=>{  if(!list[key]){    result = false  }})return result

同樣的作法,可以試著使用 reduce來做

首先是初始值為 true

Object.keys(imagesLoadedList).reduce(..., true)

在每次運算的過程,reduce的第一個值是上次運算的結果,第二個值是這次傳入的值,在使用 Object.keys的狀況下,每次傳入的值都是 property 的 key

list = { [key]: boolean }

所以在這裡的運算應該是上次運算的結果 value,和這次的 property的 value,即 list[key] 作比較

value && list[key]

整個寫下來就是

Object.keys(list).reduce((value, key) => {  return value && list[key]}, true)

沒錯,這其實是很初級的 JS,我深刻地反省…

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response