如何实现每小时配置多项任务?JavaScript代码优化求助
每小时配置多项任务的实现方案
你的需求是按小时递增展示任务数量,从1个逐步增加到3个,原代码仅处理了单个任务的判断,无法实现多任务叠加。以下是修改后的实现方案:
修改后的代码
let daySchedule = [ "08:00", "09:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00" ]; let taskDescriptions = [ "Checking vegetables", "Baking bread", "Cleaning", "Free hour" ]; // 遍历每个时间节点 for (let i = 0; i < daySchedule.length; i++) { // 计算当前时间需要展示的任务数:索引+1,最多取前3个任务(排除Free hour) const taskNum = Math.min(i + 1, taskDescriptions.length - 1); // 取出对应数量的任务并拼接成字符串 const taskList = taskDescriptions.slice(0, taskNum).join(', '); // 按预期格式输出 console.log(`${daySchedule[i]} - ${taskList}`); }
核心逻辑说明
- 用
for循环遍历时间数组,每个时间点的索引i对应任务数量的递增(08:00是索引0,对应1个任务;09:00是索引1,对应2个任务,以此类推) Math.min(i+1, taskDescriptions.length-1)避免超出有效任务范围(因为最后一项是"Free hour",不需要纳入任务列表)slice(0, taskNum)截取对应数量的任务描述,再通过join(', ')拼接成符合格式的字符串- 使用模板字符串
${}简化输出格式的拼接
运行后会输出符合你预期的结果:
08:00 - Checking vegetables
09:00 - Checking vegetables, Baking bread
10:00 - Checking vegetables, Baking bread, Cleaning
11:00 - Checking vegetables, Baking bread, Cleaning
...(后续时间点均保持三个任务)
如果需要后续时间点有其他规则(比如循环任务、切换空闲时段),可以调整taskNum的计算逻辑或任务截取方式。
内容的提问来源于stack exchange,提问作者Victorderidder76
相关产品推荐
相关产品推荐

