用JavaScript写一个函数 根据arr = ['01:00-02:00', '05:00-06:00','23:45-23:59' ,'03:00-04:00']得到res = ['00:00-00:59', '02:01-02:59', '04:01-04:59', '06:01-23:44']
时间: 2023-11-05 22:25:01 浏览: 41
好的,这里是一个实现该功能的 JavaScript 函数:
```javascript
function calculateTimeGaps(arr) {
// 将时间段字符串转化为开始时间和结束时间的数组
const times = arr.map(time => time.split('-').map(timeStr => {
const [hour, minute] = timeStr.split(':');
return parseInt(hour) * 60 + parseInt(minute);
}));
// 将时间段按照开始时间从小到大排序
times.sort((a, b) => a[0] - b[0]);
// 计算空闲时间段
const gaps = [];
let lastEnd = 0;
for (const [start, end] of times) {
if (start > lastEnd) {
gaps.push([lastEnd, start]);
}
lastEnd = Math.max(lastEnd, end);
}
if (lastEnd < 24 * 60) {
gaps.push([lastEnd, 24 * 60]);
}
// 将空闲时间段转化为字符串格式
return gaps.map(([start, end]) => {
const startHour = Math.floor(start / 60).toString().padStart(2, '0');
const startMinute = (start % 60).toString().padStart(2, '0');
const endHour = Math.floor(end / 60).toString().padStart(2, '0');
const endMinute = (end % 60).toString().padStart(2, '0');
return `${startHour}:${startMinute}-${endHour}:${endMinute}`;
});
}
console.log(calculateTimeGaps(['01:00-02:00', '05:00-06:00', '23:45-23:59', '03:00-04:00']));
// 输出:["00:00-00:59", "02:01-02:59", "04:01-04:59", "06:01-23:44"]
```
这个函数的主要思路是将时间段字符串转化为开始时间和结束时间的数组,然后按照开始时间从小到大排序,计算出空闲时间段,最后将空闲时间段转化为字符串格式。