Tally String Times with Reduce


Posted by wayne201299 on 2023-10-02

DEMO

為所有的影片添加時間

實作

  1. 選取所有的影片element,透過dataset取得每部影片的時間,並將回傳的NodeList轉型成Array

     const timeNode = Array.from(document.querySelectorAll("[data-time]"));
    
  2. 計算影片的總秒數

     const seconds = timeNode
         .map((node) => node.dataset.time)
         .map((timeCode) => {
             const [mins, secs] = timeCode.split(":").map(parseFloat);
             return mins * 60 + secs;
         })
         .reduce((total, vidSeconds) => total + vidSeconds);
    
  3. 將總秒數轉換成時、分、秒

     let secondsLeft = seconds;
     const hours = Math.floor(secondsLeft / 3600);
    
     secondsLeft = secondsLeft % 3600;
     const minutes = Math.floor(secondsLeft / 60);
    
     secondsLeft = secondsLeft % 60;
    
     console.log(hours, minutes, secondsLeft);
    

知識點

  • querySelectorAll回傳的是NodeList,裡面並不包含所有Array的API

總結

  • 了解如何透過dataset取得element屬性
  • Array的map、reduce

#javascript







Related Posts

Git 與 GitHub

Git 與 GitHub

Git branch

Git branch

NPM & NPX

NPM & NPX


Comments