JS_base_day08

本文深入讲解数组和字符串的基本操作,包括存储方式、创建、访问、遍历及常用API,如push、pop、split、join等。同时,提供实例帮助理解如何进行字符串的大小写转换、截取和匹配模式,以及数组的排序、反转和拼接。

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

复习
对象的存储方式(栈内存,堆内存)
数组
创建和访问
对象直接量 [元素1,元素2…]
构造函数 new Array(元素1,元素2…); var arr=new Array(3)
访问 第一个 arr[0] 最后一个 arr[arr.length-1] arr.length
添加新的元素 arr[arr.length]
数组分为 索引数组(以数字作为下标),关联数组(以字符串作为下标)
arr[‘name’]=‘tom’
数组的遍历
for(var i=0;i<arr.length;i++){//i下标
arr[i]
}
for(var key in arr){
arr[key]
}
for-of
数组函数(方法)——API
数组转为字符串 toString() join(’|’)
拼接数组 concat(names1,names2…)
截取数组元素 slice(-3,-1)
删除(替换,插入)数组元素 splice(2,0,‘tom’,‘jerry’)
翻转数组元素 reverse()
数组排序 sort(function(a,b){ return b-a; }) Unicode码从小到大

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

1.数组API
push(参数) 在数组的最后添加元素
pop() 删除数组最后一个元素
unshift(参数) 在数组的最前边添加元素
shift() 删除数组第一个元素
以上四个操作后,原数组会发生变化
2.二维数组
在数组中的元素,形式也是数组。
3.字符串对象
把字符串、数值、布尔型包装成对象,都称为包装对象
创建字符串
var str1=‘hello’; //直接量
var str2=new String(‘world’); //构造函数——类型是对象
var str3=String(‘hello’);
字符串API
toUpperCase() 将英文字符串转为大写
toLowerCase() 将英文字符串转为小写
练习:初始化4个英文字符,弹出提示框,如果输入的值不正确,继续弹框,直到输入正确,才会结束弹框。——不区分大小写
无限循环 while(true){}
结束循环 break
转义字符 —— \
改变字符原来的意义
’ -> ’ 普通的引号
n -> \n 换行
t -> \t 制表符(键盘的tab键)
charAt(参数) 查找下标对应的字符
charCodeAt(参数) 查找下标对应字符的Unicode码
indexOf(参数1,[参数2]) 查找某个字符对应的下标,参数2开始查找的下标,找不到返回-1
lastIndexOf(参数1) 查找某个字符最后一次出现位置的下标
练习:检测一个邮箱的格式是否合法?是否含有@;是返回true,不是返回false
slice(start, end) 截取字符串,start开始的下标,end是结束的下标;范围start~end-1。如果end为空,从start到结尾;负数表示倒数第几个。
substring(start, end) 和slice作用几乎一致,区别在于不支持负数写法,如果参数为负数,自动转成0。
练习:通过身份证号,来获取出生日期。打印 ****年
练习:通过邮箱地址来获取邮箱的用户名和域名。
jerry@sina.com
获取@的下标值,用户名:0下标值,域名:下标值+1最后
练习:把一个英文单词的首字母转为大写,其它的字母转为小写。
heLLo -> Hello
截取第一个字母(转大写),截取剩余的字母(转小写),最后把两部分拼接成新的字符串。
split(参数) 将字符串按照指定的字符转换为数组——切割字符串,参数指定的字符。
练习:把一句英文每个单词的首字母全部转为大写,其它转为小写。
wE arE faMily
按照空格切割字符串——返回数组
遍历数组,每一个元素就是单词
把单词转成上边的格式
最后每个元素拼接成字符串
4.匹配模式(了解)
replace(参数1,参数2) 查找某个字符串并替换;参数1表示要查找的字符串,参数2表示要替换的字符串。
str.replace(/china/ig, ‘中国’);
i->ingore 忽略大小写 g->global 全局查找
match(参数) 查找某个字符串,返回的结果是数组。可以使用ig
search(参数) 查找某个字符串,返回查找到的第一个字符串的下标值,如果找不到返回 -1。只能使用i
5.Math对象
不需要使用new来创建对象,直接使用Math对象
Math.PI 取圆周率
Math.abs() 取绝对值
Math.floor() 向下取整
Math.ceil() 向上取整
Math.round() 四舍五入取整
Math.max() 求一组数字的最大值
Math.min() 求一组数字的最小值
Math.random() 取随机数 范围 0~1
课后任务:
(1)复习今天的内容,完成思维导图
(2)课后练习:
使用数组保存10个人名(下标是数字),每次随机取一个(随机取下标) 0~9
(3)预习date对象以及ES6

// 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、付费专栏及课程。

余额充值