我想轉換這個:
00:07:57,685
到秒。它應該回傳00*60 07*60 57,685
問題是它的格式我沒有設法撰寫一個優化的函式。
uj5u.com熱心網友回復:
const input = "00:07:57,685";
const [hours, minutes, secondsRaw] = input.split(/:/g);
const seconds = secondsRaw.replace(",", ".");
let output = 0;
output = parseInt(hours) * 3600;
output = parseInt(minutes) * 60;
output = parseFloat(seconds);
console.log(`${output} seconds`);
uj5u.com熱心網友回復:
這是一個作業示例:
function stringTimeToSecond (stringTime) {
// convert from "," float notation to "." float notation
// split your string to [h, m, s]
// reverse to get [s, m, h] to be able to use indice on the reduce method
const stringTimeArray = stringTime.replace(',','.').split(":").reverse();
// 60^0 = 1 for seconds
// 60^1 = 60 for minutes
// 60^2 = 3600 for hours
return stringTimeArray.reduce((timeInSecond, time, i) => {
timeInSecond = time * Math.pow(60, i);
return timeInSecond;
}, 0);
}
Reduce 方法將遍歷您的陣列,然后回傳您的累加器“timeInSecond”。累加器被初始化為 0 作為 reduce 函式的第二個引數。
uj5u.com熱心網友回復:
如果我正確理解您的問題,我認為這可能會奏效:
let timestamp = "00:07:57,685"
let seconds = timestamp.split(":")[2].split(",")[0]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/368950.html
標籤:javascript
上一篇:ReactFunction組件不更新視圖onClick
下一篇:使用Javascript的1位數
