今日任務: 將每個元素的時間累加起來
<ul class="videos">
<li data-time="5:43">Video 1</li>
<li data-time="2:33">Video 2</li>
<li data-time="3:45">Video 3</li>
...
<li data-time="12:39">Video 56</li>
<li data-time="1:56">Video 57</li>
<li data-time="4:04">Video 58</li>
</ul>
querySelector要轉為陣列Array.from才能用map()
const timeList = Array.from(document.querySelectorAll('li[data-time]'));
const seconds = timeList.map((list) => list.dataset.time);
console.log(seconds);
Day04有學到split()
split()
:可根據指定的分隔符號,將字串切割成一個字串陣列。
const timeList = Array.from(document.querySelectorAll('li[data-time]'));
const seconds = timeList
.map((list) => list.dataset.time)
.map((timeCode) => {
const [mins, seconds] = timeCode.split(':');
return mins * 60 + seconds;
});
console.log(seconds);
發現是字串,要轉為數字
parseFloat()
: 將輸入的字串轉成整數
const timeList = Array.from(document.querySelectorAll('li[data-time]'));
const seconds = timeList
.map((list) => list.dataset.time)
.map((timeCode) => {
const [mins, seconds] = timeCode.split(':').map(parseFloat);
return mins * 60 + seconds;
});
console.log(seconds);
Day04有學到reduce()
reduce()
: 將一個累加器及陣列中每項元素(由左至右)傳入回呼函式,將陣列化為單一值。
將時間都加在一起
const timeList = Array.from(document.querySelectorAll('li[data-time]'));
const seconds = timeList
.map((list) => list.dataset.time)
.map((timeCode) => {
const [mins, seconds] = timeCode.split(':').map(parseFloat);
return mins * 60 + seconds;
})
.reduce((total, secs) => total + secs);
console.log(seconds);
Math.floor()
: 會無條件捨去。
console.log(Math.floor(1.25)); //顯示1
console.log(Math.floor(-1.25)); //顯示-2
餘數運算子(%)
: 會返回餘數
Math.floor(秒數/3600)=小時數
秒數%3600=扣掉小時數後的餘數
let secsLeft = seconds;
const hours = Math.floor(seconds / 60 / 60);
secsLeft = seconds % 3600;
const minutes = Math.floor(secsLeft / 60);
secsLeft = secsLeft % 60;
console.log(hours, minutes, secsLeft);
所有影片總時長:4時58分58秒
今日學習到的:
效果連結:連結
參考連結:
JS30