เราจำเป็นต้องเขียนฟังก์ชันที่ใช้สตริง '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