JS_base_day04

本文详细介绍了编程中流程控制的基本概念,包括顺序、选择和循环执行方式。深入探讨了if语句、switch语句及while、do-while、for循环的用法,以及break和continue在循环控制中的应用。通过实例讲解了循环嵌套和常见循环练习,如猜数字游戏、计算斐波那契数列等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

复习
程序三种执行方式:顺序执行,选择执行,循环执行。
选择执行:
if(逻辑表达式) { 语句; }
逻辑表达式可以直接写true和false,
undefined,null,0,’’,NaN
if(逻辑表达式) { 语句1; } else{ 语句2; }
逻辑表达式 ? 语句1 : 语句2
if(逻辑表达式1){语句1;}else if(逻辑表达式2){语句2;}…else{ }
switch(表达式){
case 1:
语句1;
break;

default:
语句n;
}

while(循环的条件){ //循环体 }

学习一门编程语言路线图
(1)了解语言的背景,历史,特点,应用领域,现状
(2)搭建开发环境,编写 hello world
(3)声明变量和常量
(4)数据类型
(5)运算符
(6)逻辑结构
(7)通用小程序
(8)函数和对象
(9)第三方的类库,插件,组件,框架
(10)开发项目

1.循环中的break
用于终止循环,出现break之后,循环到此结束。
练习:
使用弹出提示框完成猜数字游戏;
游戏规则:初始化一个数字(var num=10),循环(无限循环)弹出提示框,如果输入的数字大,提示’big’,如果输入的数字小,提示’small’,否则提示’right’,结束循环(break)
提示使用弹出警示窗口 alert()
2.do…while循环
do{
//循环体
}while(循环条件)
执行过程:
执行循环体,判断循环条件是否为true,如果为true,继续执行循环体,如果为false,终止循环。
while和do-while的区别
①while先判断再执行
②do-while 先执行一次,然后再判断
③如果条件为false的时候,while立即终止,而do-while会执行一次然后终止。
练习:
输入密码,先输入完密码之后,才能进行判断是否正确。
使用弹出提示框,输入密码,如果输入的正确,结束循环,否则继续弹出提示框。
初始化密码,无限循环弹出提示框,直到输入正确的密码结束循环。
3.for循环
for(表达式1;表达式2;表达式3){
//循环体
}
表达式1:循环的初始值,例如 i=0;
表达式2:循环的条件,例如i<10
表达式3:循环的变化(自增,自减),例如i++

练习1:计算1~100之间所有奇数的和?//判断奇数:i%2取余为1
练习2:计算1~100之间所有能被7整除,并且是奇数的和。
练习3:计算20的阶乘。 //201918…1;
练习4:打印一行 *****
1
5=5 25=10 35=15 45=20 55=25
’ ’
4.break和continue在循环中的应用
break 结束整个循环,break后的语句也不能被执行。
continue 结束这一次的循环,还执行自增或者自减
练习1:计算1~10之间所有奇数的和;//如果遇到的数字是偶尔,跳过
练习2:计算1~100之间所有数字的和,当总和大于4000的时候,终止循环,输出总和,同时输出此时的i值。
练习3:打印2000~2100之间所有的闰年
能被4整除,并且不能被100整除,或者能被400整除
5.循环嵌套
while,do-while,for之间可以相互嵌套。






**




1
2 4
3 6 9
4 8 12 16
5
6
7
8
9

斐波那契数列
1 1 2 3 5 8 13 21 34 55
n1 n2
n1 n2
n1 n2
n1 n2
n1 n2
使用for循环来计算第12个月的数字是多少?
从3开始循环,<=12

课后任务:
(1)完成今天的复习,并整理思维导图
(2)完成九九乘法表(完整版)
计算斐波那契数列的第12项是多少(选做)
(3)预习js的自定义函数

// API 基础路径 const API_BASE_URL = '/api'; new Vue({ el: '#app', data: { currentView: 'home', showLogin: false, showRegister: false, showCreateClub: false, showCreateActivity: false, clubTab: 'all', activityTab: 'all', profileTab: 'clubs', adminTab: 'clubs', loginForm: { username: '', password: '' }, registerForm: { name: '', studentId: '', email: '', phone: '', password: '', confirm: '' }, newClub: { name: '', description: '' }, newActivity: { title: '', description: '', location: '', startTime: '', endTime: '' }, currentUser: null, isSysAdmin: false, isClubAdmin: false, stats: null, clubs: [], activities: [], popularClubs: [], recentActivities: [], userClubs: [], userActivities: [], userApplications: [], pendingClubs: [], pendingApplications: [], loadingClubs: false, loadingActivities: false, loadingUserClubs: false, loadingUserActivities: false, loadingUserApplications: false, loadingPendingClubs: false, loadingPendingApplications: false }, computed: { filteredClubs() { if (this.clubTab === 'my' && this.currentUser) { return this.clubs.filter(club => club.isMember); } return this.clubs; }, filteredActivities() { if (this.activityTab === 'joined' && this.currentUser) { return this.activities.filter(act => this.userActivities.some(ua => ua.id === act.id) ); } if (this.activityTab === 'my' && this.isClubAdmin) { return this.activities; } return this.activities; } }, async created() { this.loadHomeData(); // 检查本地存储是否有登录信息 const savedUser = localStorage.getItem('currentUser'); if (savedUser) { this.currentUser = JSON.parse(savedUser); this.checkAdminStatus(); } }, methods: { async loadHomeData() { try { // 加载统计数据 const statsRes = await axios.get(`${API_BASE_URL}/stats`); this.stats = statsRes.data; // 加载热门社团 const popularClubsRes = await axios.get(`${API_BASE_URL}/clubs/popular`); this.popularClubs = popularClubsRes.data; // 加载近期活动 const recentActivitiesRes = await axios.get(`${API_BASE_URL}/activities/recent`); this.recentActivities = recentActivitiesRes.data; } catch (error) { console.error('加载首页数据失败:', error); } }, async loadClubs() { this.loadingClubs = true; try { const res = await axios.get(`${API_BASE_URL}/clubs`, { headers: this.getAuthHeader() }); this.clubs = res.data; } catch (error) { console.error('加载社团数据失败:', error); } finally { this.loadingClubs = false; } }, async loadActivities() { this.loadingActivities = true; try { const res = await axios.get(`${API_BASE_URL}/activities`, { headers: this.getAuthHeader() }); this.activities = res.data; } catch (error) { console.error('加载活动数据失败:', error); } finally { this.loadingActivities = false; } }, async loadUserClubs() { this.loadingUserClubs = true; try { const res = await axios.get(`${API_BASE_URL}/users/${this.currentUser.id}/clubs`, { headers: this.getAuthHeader() }); this.userClubs = res.data; } catch (error) { console.error('加载用户社团数据失败:', error); } finally { this.loadingUserClubs = false; } }, async loadUserActivities() { this.loadingUserActivities = true; try { const res = await axios.get(`${API_BASE_URL}/users/${this.currentUser.id}/activities`, { headers: this.getAuthHeader() }); this.userActivities = res.data; } catch (error) { console.error('加载用户活动数据失败:', error); } finally { this.loadingUserActivities = false; } }, async loadUserApplications() { this.loadingUserApplications = true; try { const res = await axios.get(`${API_BASE_URL}/users/${this.currentUser.id}/applications`, { headers: this.getAuthHeader() }); this.userApplications = res.data; } catch (error) { console.error('加载用户申请数据失败:', error); } finally { this.loadingUserApplications = false; } }, async loadPendingClubs() { this.loadingPendingClubs = true; try { const res = await axios.get(`${API_BASE_URL}/admin/pending-clubs`, { headers: this.getAuthHeader() }); this.pendingClubs = res.data; } catch (error) { console.error('加载待审核社团数据失败:', error); } finally { this.loadingPendingClubs = false; } }, async loadPendingApplications() { this.loadingPendingApplications = true; try { const res = await axios.get(`${API_BASE_URL}/admin/pending-applications`, { headers: this.getAuthHeader() }); this.pendingApplications = res.data; } catch (error) { console.error('加载待审核申请数据失败:', error); } finally { this.loadingPendingApplications = false; } }, changeView(view) { this.currentView = view; if (view === 'clubs') { this.loadClubs(); } else if (view === 'activities') { this.loadActivities(); } else if (view === 'admin') { this.adminTab = 'clubs'; this.loadPendingClubs(); } }, async login() { try { const res = await axios.post(`${API_BASE_URL}/auth/login`, this.loginForm); if (res.data.success) { this.currentUser = res.data.user; this.isSysAdmin = this.currentUser.role === 'sys_admin'; this.isClubAdmin = this.currentUser.role === 'club_admin' || this.currentUser.role === 'sys_admin'; this.showLogin = false; // 保存用户信息到本地存储 localStorage.setItem('currentUser', JSON.stringify(this.currentUser)); // 加载用户数据 this.loadUserClubs(); this.loadUserActivities(); this.loadUserApplications(); this.$message.success('登录成功!'); } else { this.$message.error('登录失败: ' + res.data.message); } } catch (error) { console.error('登录失败:', error); this.$message.error('登录失败,请检查网络连接'); } }, async register() { if (this.registerForm.password !== this.registerForm.confirm) { this.$message.error('两次输入的密码不一致'); return; } try { const res = await axios.post(`${API_BASE_URL}/auth/register`, this.registerForm); if (res.data.success) { this.currentUser = res.data.user; this.isSysAdmin = false; this.isClubAdmin = false; this.showRegister = false; // 保存用户信息到本地存储 localStorage.setItem('currentUser', JSON.stringify(this.currentUser)); this.$message.success('注册成功!'); } else { this.$message.error('注册失败: ' + res.data.message); } } catch (error) { console.error('注册失败:', error); this.$message.error('注册失败,请检查网络连接'); } }, logout() { this.currentUser = null; this.isSysAdmin = false; this.isClubAdmin = false; this.currentView = 'home'; // 清除本地存储 localStorage.removeItem('currentUser'); this.$message.success('已退出登录'); }, showProfile() { this.currentView = 'profile'; this.profileTab = 'clubs'; this.loadUserClubs(); }, loadHomeData() { this.$axios.get('/api/stats') .then(response => { // 成功处理 }) .catch(error => { // 关键:记录完整错误信息 console.error('[详细错误]', { status: error.response?.status, data: error.response?.data, headers: error.response?.headers }); }); }, checkAdminStatus() { this.isSysAdmin = this.currentUser.role === 'sys_admin'; this.isClubAdmin = this.currentUser.role === 'club_admin' || this.currentUser.role === 'sys_admin'; }, getAuthHeader() { if (this.currentUser && this.currentUser.token) { return { Authorization: `Bearer ${this.currentUser.token}` }; } return {}; }, async createClub() { try { const res = await axios.post(`${API_BASE_URL}/clubs`, this.newClub, { headers: this.getAuthHeader() }); if (res.data.success) { this.showCreateClub = false; this.newClub = { name: '', description: '' }; this.$message.success('社团创建申请已提交,等待管理员审核'); // 刷新社团列表 this.loadClubs(); } else { this.$message.error('创建社团失败: ' + res.data.message); } } catch (error) { console.error('创建社团失败:', error); this.$message.error('创建社团失败,请稍后再试'); } }, async applyToClub(club) { try { const res = await axios.post(`${API_BASE_URL}/clubs/${club.id}/apply`, {}, { headers: this.getAuthHeader() }); if (res.data.success) { club.isMember = true; this.$message.success(`已申请加入 ${club.name},等待审核`); // 刷新用户社团列表 this.loadUserClubs(); } else { this.$message.error('申请失败: ' + res.data.message); } } catch (error) { console.error('申请加入社团失败:', error); this.$message.error('申请加入社团失败,请稍后再试'); } }, async leaveClub(club) { try { const res = await axios.delete(`${API_BASE_URL}/clubs/${club.id}/members/${this.currentUser.id}`, { headers: this.getAuthHeader() }); if (res.data.success) { club.isMember = false; this.$message.success(`已退出 ${club.name}`); // 刷新用户社团列表 this.loadUserClubs(); } else { this.$message.error('退出社团失败: ' + res.data.message); } } catch (error) { console.error('退出社团失败:', error); this.$message.error('退出社团失败,请稍后再试'); } }, async joinActivity(activity) { try { const res = await axios.post(`${API_BASE_URL}/activities/${activity.id}/join`, {}, { headers: this.getAuthHeader() }); if (res.data.success) { activity.participantCount++; this.$message.success(`已报名参加 ${activity.title}`); // 刷新用户活动列表 this.loadUserActivities(); } else { this.$message.error('报名失败: ' + res.data.message); } } catch (error) { console.error('报名活动失败:', error); this.$message.error('报名活动失败,请稍后再试'); } }, async signActivity(activity) { try { const res = await axios.post(`${API_BASE_URL}/activities/${activity.id}/sign`, {}, { headers: this.getAuthHeader() }); if (res.data.success) { activity.signStatus = 'attended'; this.$message.success(`活动 ${activity.title} 签到成功!`); // 刷新用户活动列表 this.loadUserActivities(); } else { this.$message.error('签到失败: ' + res.data.message); } } catch (error) { console.error('签到失败:', error); this.$message.error('签到失败,请稍后再试'); } }, viewClub(club) { this.$message.info(`查看社团详情: ${club.name}`); }, viewActivity(activity) { this.$message.info(`查看活动详情: ${activity.title}`); }, viewApplication(app) { this.$message.info(`查看申请详情: ${app.name}`); }, activityStatusText(status) { const statusMap = { 'active': '进行中', 'pending': '待审核', 'approved': '已批准', 'rejected': '已拒绝', 'ended': '已结束' }; return statusMap[status] || '未知状态'; }, async approveClub(club) { try { const res = await axios.put(`${API_BASE_URL}/admin/clubs/${club.id}/approve`, {}, { headers: this.getAuthHeader() }); if (res.data.success) { this.$message.success(`已批准 ${club.name} 的创建申请`); // 刷新待审核列表 this.loadPendingClubs(); // 刷新社团列表 this.loadClubs(); } else { this.$message.error('批准失败: ' + res.data.message); } } catch (error) { console.error('批准社团失败:', error); this.$message.error('批准社团失败,请稍后再试'); } }, async rejectClub(club) { try { const res = await axios.put(`${API_BASE_URL}/admin/clubs/${club.id}/reject`, {}, { headers: this.getAuthHeader() }); if (res.data.success) { this.$message.success(`已拒绝 ${club.name} 的创建申请`); // 刷新待审核列表 this.loadPendingClubs(); } else { this.$message.error('拒绝失败: ' + res.data.message); } } catch (error) { console.error('拒绝社团失败:', error); this.$message.error('拒绝社团失败,请稍后再试'); } }, async approveApplication(app) { try { const res = await axios.put(`${API_BASE_URL}/admin/applications/${app.id}/approve`, {}, { headers: this.getAuthHeader() }); if (res.data.success) { this.$message.success(`已批准 ${app.userName} 加入 ${app.clubName}`); // 刷新待审核列表 this.loadPendingApplications(); } else { this.$message.error('批准失败: ' + res.data.message); } } catch (error) { console.error('批准申请失败:', error); this.$message.error('批准申请失败,请稍后再试'); } }, async rejectApplication(app) { try { const res = await axios.put(`${API_BASE_URL}/admin/applications/${app.id}/reject`, {}, { headers: this.getAuthHeader() }); if (res.data.success) { this.$message.success(`已拒绝 ${app.userName} 加入 ${app.clubName}`); // 刷新待审核列表 this.loadPendingApplications(); } else { this.$message.error('拒绝失败: ' + res.data.message); } } catch (error) { console.error('拒绝申请失败:', error); this.$message.error('拒绝申请失败,请稍后再试'); } }, async createActivity() { try { const res = await axios.post(`${API_BASE_URL}/activities`, this.newActivity, { headers: this.getAuthHeader() }); if (res.data.success) { this.showCreateActivity = false; this.newActivity = { title: '', description: '', location: '', startTime: '', endTime: '' }; this.$message.success('活动已发布,等待审核'); // 刷新活动列表 this.loadActivities(); } else { this.$message.error('发布活动失败: ' + res.data.message); } } catch (error) { console.error('发布活动失败:', error); this.$message.error('发布活动失败,请稍后再试'); } }, formatDate(dateString) { if (!dateString) return ''; const date = new Date(dateString); return date.toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }); }, editProfile() { this.$message.info('编辑个人信息功能'); }, loadMyActivities() { // 简化实现,实际中应该调用API this.loadingActivities = true; setTimeout(() => { this.activities = this.activities.filter(activity => activity.clubAdminId === this.currentUser.id ); this.loadingActivities = false; }, 500); } } });
06-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值