如果希望将时间点放在一个对象中,并且每个对象包含 `time` 和 `checked` 属性(`checked` 默认为 `false`),可以修改代码如下:
```javascript
function generateTimeSlots() {
const morningSlots = []; // 6:00 ~ 12:30
const afternoonSlots = []; // 13:00 ~ 18:30
const eveningSlots = []; // 19:00 ~ 23:59
const startHour = 6; // 早上6点
const endHour = 24; // 晚上12点
// 获取当前时间
const now = new Date();
const currentHour = now.getHours();
const currentMinute = now.getMinutes();
const currentTime = `${currentHour.toString().padStart(2, '0')}:${currentMinute.toString().padStart(2, '0')}`;
for (let hour = startHour; hour < endHour; hour++) {
for (let minute = 0; minute < 60; minute += 30) {
const time = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
// 如果当前时间点已经过去,则跳过
if (time < currentTime) {
continue;
}
// 创建时间点对象
const timeObj = { time, checked: false };
// 根据时间段分组
if (hour < 12 || (hour === 12 && minute <= 30)) {
morningSlots.push(timeObj); // 6:00 ~ 12:30
} else if (hour < 18 || (hour === 18 && minute <= 30)) {
afternoonSlots.push(timeObj); // 13:00 ~ 18:30
} else {
eveningSlots.push(timeObj); // 19:00 ~ 23:30
}
}
}
return {
morningSlots,
afternoonSlots,
eveningSlots,
};
}
// 调用方法
const { morningSlots, afternoonSlots, eveningSlots } = generateTimeSlots();
console.log("早上时间段 (6:00 ~ 12:30):", morningSlots);
console.log("下午时间段 (13:00 ~ 18:30):", afternoonSlots);
console.log("晚上时间段 (19:00 ~ 23:59):", eveningSlots);
```
### 修改点:
1. **时间点对象**:
- 每个时间点以对象形式存储,包含 `time` 和 `checked` 属性。
- 例如:`{ time: '15:00', checked: false }`。
2. **动态过滤当前时间之前的时间点**:
- 获取当前时间,并跳过已经过去的时间点。
3. **返回结果**:
- 返回 `morningSlots`、`afternoonSlots` 和 `eveningSlots`,每个数组中的元素都是时间点对象。
### 示例输出:
假设当前时间是 `14:45`,则输出如下:
```javascript
早上时间段 (6:00 ~ 12:30): [] // 当前时间已超过12:30,早上时间段为空
下午时间段 (13:00 ~ 18:30): [
{ time: '15:00', checked: false },
{ time: '15:30', checked: false },
{ time: '16:00', checked: false },
{ time: '16:30', checked: false },
{ time: '17:00', checked: false },
{ time: '17:30', checked: false },
{ time: '18:00', checked: false },
{ time: '18:30', checked: false }
]
晚上时间段 (19:00 ~ 23:59): [
{ time: '19:00', checked: false },
{ time: '19:30', checked: false },
{ time: '20:00', checked: false },
{ time: '20:30', checked: false },
{ time: '21:00', checked: false },
{ time: '21:30', checked: false },
{ time: '22:00', checked: false },
{ time: '22:30', checked: false },
{ time: '23:00', checked: false },
{ time: '23:30', checked: false }
]
```
### 总结:
- 每个时间点以对象形式存储,包含 `time` 和 `checked` 属性。
- 动态过滤掉当前时间之前的时间点。
- 返回的结果是 `morningSlots`、`afternoonSlots` 和 `eveningSlots`,分别对应早上、下午和晚上的时间段。