JS_base_day05

本文提供了一条学习编程语言的清晰路径,从理解语言背景到实际项目开发,涵盖变量、数据类型、逻辑结构、函数等核心概念,深入讲解了函数定义、调用、作用域及递归技巧。

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

复习
while(循环条件){
//循环体
}
do{ //先执行一次,不管条件是否为true
//循环体
}while(循环条件);

for(初始值;循环条件;循环变化){
//循环体
}
循环嵌套

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

学习目标
函数
变量的作用域
函数的作用域
递归(掌握)
1.函数
分为两种
一种是js提供的,例如typeof parseInt,parseFloat,alert…;这些事可以直接使用的。
另一种是自定义函数(function),也称为方法(method);
自定义函数是一段已经预定义好的代码块,并且可以反复执行。
2.定义函数和使用函数
(1)普通函数的声明和调用
声明
function 函数名称( ){ //和声明变量规则一致
//函数体 —— 要重复执行的代码
}
调用
函数名称( )
函数只是声明,里边的代码不执行。只要调用函数才会执行函数体中的代码。
练习:声明一个函数calc,在函数体中实现两个数字相加,并打印结果。
(2)带有参数的函数声明和调用
声明
function 函数名称(参数列表){
//函数体
}
调用
函数名称(参数列表)

参数列表:可以声明0个或者多个,多个之间用逗号隔开;声明时的参数称为“形参”,调用时的参数称为“实参”;
形参只是负责占位,在调用的时候,实参的值会赋给形参
练习:声明函数calc,传递两个参数,计算相加并打印最终的结果。
(3)带有返回值的函数的声明和调用
声明
function 函数名称(参数列表){
//函数体
return 值;
}
调用
函数名称(参数列表)
说明:
①函数中没有添加return,返回结果是undefined;
②函数有return,如果return后的值为空,返回结果是undefined
③return后的所有语句都不能被执行到,return就是函数结束。
练习1:声明函数getMax,传递两个参数,计算两个参数的大小,返回最大值。
练习2:声明函数getMax,传递3个参数,返回最大值。
练习3:声明函数sum,传递1个参数,返回这个参数和1之间的所有数的和。
练习4:声明函数isRun,传递参数为年份,如果是闰年返回true,不是返回false
3.变量的作用域
变量的作用域指变量的可访问范围。
分为全局作用域和局部(函数)作用域
全局作用域下的变量可以在任何位置访问到
局部作用域下的变量只能在局部(函数内部)访问到
注意:函数内部声明的变量没有使用var关键字,声明的变量就成为全局变量。
变量提升
js程序在执行前,声明的变量都会加载到程序的最前边(只是提升声明),但是赋值还是在原来的位置。函数内部也存在变量的提升。
4.函数作用域
函数和变量相同,也分为全局作用域和局部作用域。
局部(函数)作用域下声明的函数,只能在函数的内部访问。
全局作用域下声明的函数,可以在任何的位置访问
在程序执行前,声明的函数会提升到程序的最前边。
5.递归
在函数的内部,调用自身。
练习:
声明函数getSum,使用递归(函数),来获取前n项的和

练习:使用递归计算前n的乘积(阶乘)
课后任务:
(1)复习今天的内容,整理出全天的思维导图
(2)使用递归计算斐波那契数列的第n项
任何一项的结果=前两项的值相加
结束递归条件:第一项和第二项返回的结果都是1;
(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、付费专栏及课程。

余额充值