เราต้องเขียนฟังก์ชันรับสตริง 'HH:MM:SS' คืนจำนวนวินาที
เช่น
countSeconds('12:00:00') // 43200
countSeconds('00:30:10') // 1810
เขียนโค้ด แยกสตริง แปลงอาร์เรย์สตริงเป็นอาร์เรย์ตัวเลข คืนวินาทีที่เหมาะสม
ตัวอย่าง
const timeString = '23:54:43';
const other = '12:30:00';
const withoutSeconds = '10:30';
const countSeconds = (str) => {
const [hh = '0', mm = '0', ss = '0'] = (str || '0:0:0').split(':');
const hour = parseInt(hh, 10) || 0;
const minute = parseInt(mm, 10) || 0;
const second = parseInt(ss, 10) || 0;
return (hour*3600) + (minute*60) + (second);
};
console.log(countSeconds(timeString));
console.log(countSeconds(other));
console.log(countSeconds(withoutSeconds));
ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็น
86083 45000 37800