簡體   English   中英

如何減少使用 Javascript 的時間?

[英]How to reduce time using Javascript?

如何使用reduce()計算以下數組中所有時間的總和(字符串格式)?

time["00:30", "01:45", "02:33"]

times.reduce((time, nextTime) => time + nextTime, 0)

我在想我需要split(":"), parseInt()和一些更多的計算,還是有更簡單的方法來做到這一點?

如果你可以使用像moment.js這樣的開放式 JavaScript 庫,下面的代碼很簡單並且可以保留你的字符串格式化時間。

請注意,我將"00:00"作為默認值傳遞給reduce() ,以便從零基線計算時間,這也遵循我們將用於數組中所有其他值的字符串格式。

const times["00:30", "01:45", "02:33"]

const totalTime = times.reduce((time, nextTime) => {
  return moment(time, "hh:mm")
          .add(nextTime, "hh:mm")
          .format("hh:mm");
}, "00:00");

console.log("total time -->", totalTime);

// total time --> "04:48"

如果我們在reduce()中添加日志記錄來查看值的累積:

"12:30"
"02:15"
"04:48"
"total time -->" "04:48"

請注意,第一次通過后的結果是“12:30”。 如果數組中的所有時間總和小於一個時鍾小時,則最終結果對於您的特定用例可能是不可接受的。

這對我有用,這個 function 計時器需要 2 次 hh:mm:ss 並將其拆分、划分,然后將它們加在一起,然后再次將其格式化為 hh:mm:ss

function timer(tempo1, tempo2) {
  var array1 = tempo1.split(":");

  var tempo_seg1 =
    parseInt(array1[0]) * 3600 + parseInt(array1[1]) * 60 + parseInt(array1[2]);

  var array2 = tempo2.split(":");

  var tempo_seg2 =
    parseInt(array2[0]) * 3600 + parseInt(array2[1]) * 60 + parseInt(array2[2]);

  var tempofinal = parseInt(tempo_seg1) + parseInt(tempo_seg2);

  var hours = Math.floor(tempofinal / (60 * 60));

  var divisorMinutes = tempofinal % (60 * 60);

  var minutes = Math.floor(divisorMinutes / 60);

  var divisorSeconds = divisorMinutes % 60;

  var seconds = Math.ceil(divisorSeconds);

  var counter = "";

  if (hours < 10) {
    counter = "0" + hours + ":";
  } else {
    counter = hours + ":";
  }

  if (minutes < 10) {
    counter += "0" + minutes + ":";
  } else {
    counter += minutes + ":";
  }

  if (seconds < 10) {
    counter += "0" + seconds;
  } else {
    counter += seconds;
  }

  return counter;
}

export default timer;

在我的 React App 上,我使用這段代碼來跟蹤時間並添加它們調用計時器 function

const updateTime = () => {
    let times = [];
    let times2 = [];
    if (todos.length > 1) {
      for (let i = 0; i < todos.length; i++) {
        times.push(todos[i].time + ":00");
      }
      times2 = times[0];
      for (let i = 1; i < times.length; i++) {
        times2 = timer(times2, times[i]);
      }
      times2 = times2.substr(0, 5);
    } else if (todos.length == 1) times2 = todos[0].time;
    else times2 = "No tasks";
    return times2;
  };

我只想要 hh:mm 但為了將來在需要時實現秒數,我將添加“:00”(秒數),然后再次使用將其刪除

times2 = times2.substr(0, 5);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM