DAY 25
2
Modern Web

## Day25: Adding Up Times With Reduce

1.先把所有li都選起來

``````const timeNodes = [...document.querySelectorAll('[data-time]')]
``````

2.先取出data-time的值，並回傳成陣列

``````const seconds = timeNodes
.map(time => time.dataset.time)
``````

3.拆解陣列中的字串，並使其成為數字

``````const seconds = timeNodes
.map(time => time.dataset.time)
.map(timeCode => {
const [mins, secs] = timeCode.split(':')
return (mins * 60) + secs*1
})
``````

4.使用reduce()做加總，算出總秒數

``````const seconds = timeNodes
.map(time => time.dataset.time)
.map(timeCode => {
const [mins, secs] = timeCode.split(':')
return (mins * 60) + secs*1
})
.reduce((prev, next) => prev + next)
``````

5.將總秒數換算成 時、分、秒

``````const hour = Math.floor(seconds/3600) // 總秒數/3600，並轉成整數，即為小時
const secondsLeft =  seconds % 3600 // 總秒數/3600的餘數，即為扣除小時後剩餘的秒數
const min = Math.floor(secondsLeft/60) // 剩餘的秒數/60，並轉成整數，即為分鐘
const second = secondsLeft % 60 // 剩餘的秒數/60的餘數，即為扣除分鐘後剩餘的秒數

console.log(`總秒數:\${seconds}秒，換算後為\${hour}時\${min}分\${second}秒`)
``````

codePen

javascript30