js数组实现课表
使用 JavaScript 数组实现课表
数据结构设计
可以使用多维数组存储课表信息,例如按星期和课程节数划分。以下是一个示例数据结构:
const timetable = [
// 星期一
[
{ name: "数学", teacher: "张老师", location: "A101" },
{ name: "英语", teacher: "李老师", location: "B202" },
null, // 空节
{ name: "物理", teacher: "王老师", location: "C303" }
],
// 星期二
[
null,
{ name: "化学", teacher: "赵老师", location: "D404" },
{ name: "生物", teacher: "刘老师", location: "E505" },
null
],
// ... 其他星期
];
动态添加课程
可以通过数组方法动态添加或修改课程:
// 添加星期三的课程
timetable[2] = [
{ name: "历史", teacher: "陈老师", location: "F606" },
null,
{ name: "地理", teacher: "杨老师", location: "G707" }
];
// 修改特定课程
timetable[0][1].location = "B205";
查询课程信息
使用数组索引查询特定时间的课程:
// 查询星期一第二节课
const mondaySecondClass = timetable[0][1];
// 查询星期三所有课程
const wednesdayClasses = timetable[2];
可视化输出
将课表数据转换为可读格式:
function printTimetable() {
const weekdays = ["星期一", "星期二", "星期三", "星期四", "星期五"];
weekdays.forEach((day, dayIndex) => {
console.log(`\n${day}:`);
timetable[dayIndex]?.forEach((cls, classIndex) => {
if (cls) {
console.log(`第${classIndex + 1}节: ${cls.name} - ${cls.teacher} (${cls.location})`);
} else {
console.log(`第${classIndex + 1}节: 空闲`);
}
});
});
}
高级功能实现
可以扩展更多实用功能:

// 查找特定老师的课程
function findClassesByTeacher(teacherName) {
return timetable.flatMap((day, dayIndex) =>
day.map((cls, classIndex) =>
cls?.teacher === teacherName ? { dayIndex, classIndex, ...cls } : null
).filter(Boolean)
);
}
// 检查时间冲突
function hasConflict(newClass) {
return timetable[newClass.day]?.[newClass.period] !== null;
}
注意事项
- 数组索引从0开始,但实际显示时可以+1更符合日常习惯
- 使用null或undefined表示空闲时段
- 多维数组结构可以根据实际需求调整,如增加周数维度
- 考虑使用TypeScript增强类型安全






