// 定义一个学生管理对象
let studentManager = {
//定义一个学生数据
students: [
{
no: '1001',
name: '张三',
age: 22,
sex: '男'
},
{
no: '1002',
name: '李四',
age: 24,
sex: '女'
},
{
no: '1003',
name: '王五',
age: 26,
sex: '男'
}
],
// 显示所有学生信息的方法
show: function () {
let str = '学号\t姓名\t年龄\t性别'
// 循环出所有的学生信息,并拼接到str中
console.log(str);
this.students.forEach(i => {
str += `\n${i.no}\t${i.name}\t${i.age}\t\t${i.sex}`;
})
alert(str)
},
add: function () {
// 输入学习的基本信息
let no = prompt('请输入学号')
// 判断学号是否重复
let index = this.students.findIndex(r => r.no === no)
while (index !== -1) {
no = prompt('学号重复,请重新输入')
index = this.students.findIndex(r => r.no === no)
}
let name = prompt('请输入姓名')
let age = parseInt(prompt('请输入年龄'))
let sex = prompt('请输入性别')
// 创建学生对象
// 将学生对象添加到数组中(学号不能重复)
let obj = {
no: no,
name: name,
age: age,
sex: sex
}
this.students.push(obj)
alert('添加成功')
},
// 修改学生信息的方法
update: function () {
let no = prompt('请输入学号')
let stu = this.students.find(r => r.no === no)
// 根据学号判断,有没有找到该学生,找到了修改该学生的其他信息,没找到提示学号不存在
while (!stu) {
no = prompt('学号不存在,请重新输入')
stu = this.students.find(r => r.no === no)
}
stu.name = prompt('请输入姓名')
stu.age = parseInt(prompt('请输入年龄'))
stu.sex = prompt('请输入性别')
alert('修改成功')
},
delete:function(){
let no = prompt('请输入学号')
let stu = this.students.findIndex(r => r.no === no)
while (stu ===-1) {
no = prompt('学号不存在,请重新输入')
stu = this.students.findIndex(r => r.no === no)
}
this.students.splice(stu,1)
alert('删除成功')
},
// 系统主菜单方法
menu: function () {
// 接收用户的输入
let no = prompt('*****学生管理系统*****\n1.查询学生 2.添加学生 3.修改学生 4.删除学生 0.退出系统')
// 判断用户输入的是什么
switch (no) {
case '1':
// 调用显示所有学生的方法
this.show()
break
case '2':
this.add()
break
case '3':
this.update()
break
case '4':
this.delete()
break
default:
alert('成功退出系统,欢迎下次使用')
return //跳转整个方法
}
// 再次调用自身方法(递归)
this.menu()
}
}
// 使用学生管理对象,调用menu方法
studentManager.menu()