[英]Problem creating time slots in JavaScript
我將創建每個兩個小時的時間段。
start_time=10:00
end_time=24:00
像[ [10:00,12:00], [12:00,14:00], [14:00,16:00] ] ...
我正在使用該功能:
function calculate_time_slot(start_time, end_time, interval = "120") {
var i, formatted_time;
var time_slots = new Array();
for (var i = start_time; i <= end_time; i = i + interval) {
formatted_time = convertHours(i);
time_slots.push(formatted_time);
}
return time_slots;
}
但它產生這樣的結果:
[
'10:00', '12:00',
'14:00', '16:00',
'18:00', '20:00',
'22:00', '24:00'
]
如何使配對像預期的結果一樣:
[ [10:00,12:00], [12:00,14:00], [14:00,16:00] ] ...
在循環內,計算兩種格式化時間:一種用於槽的開始,一種用於槽的結束:
function calculate_time_slot(startTime, endTime, interval = 120) {
const timeSlots = [];
for (let i = startTime; i < endTime; i += interval) {
const formattedBegin = convertHours(i);
const formattedEnd = convertHours(i + interval);
timeSlots.push([formattedBegin, formattedEnd]);
}
return timeSlots;
}
確保將interval
設置為數字,而不是字符串,以便添加而不是連接。
您可以在calculate_time_slot
函數中使用reduce()
,如下所示:
let time_slots = ["10:00", "12:00", "14:00", "16:00", "18:00", "20:00", "22:00", "24:00"]; time_slots = time_slots.reduce((acc, cur, i, arr) => { if (i < arr.length - 1) { acc.push([`${cur}`, `${arr[i + 1]}`]); } return acc; }, []); console.log(time_slots);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.