#javascript
#язык JavaScript
Вопрос:
Я хочу преобразовать это:
00:07:57,685
до секунд. Он должен вернуться 00*60 07*60 57,685
Проблема в том, что в его формате мне не удалось написать оптимизированную функцию.
Комментарии:
1. Можете ли вы уточнить формат ввода? Неужели это
HH:MM:SS,sss
так ?2. Да, именно так и есть.
Ответ №1:
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`);
Ответ №2:
Вот рабочий образец :
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) =gt; { timeInSecond = time * Math.pow(60, i); return timeInSecond; }, 0); }
Метод Reduce выполнит итерацию по вашему массиву, а затем вернет ваш накопитель «timeInSecond». Накопитель инициализируется значением 0 в качестве второго аргумента функции reduce.
Ответ №3:
Я думаю, что это могло бы сработать, если бы я правильно понял ваш вопрос:
let timestamp = "00:07:57,685" let seconds = timestamp.split(":")[2].split(",")[0]