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

想要自學程式?七個自學程式設計正確的觀念和心態

想要自學程式?七個自學程式設計正確的觀念和心態

Tomcat 設定

Tomcat 設定

CS50 IP (Internet Protocol)

CS50 IP (Internet Protocol)


Comments