第 12 周总结:函数扩展与字符串/数组扩展 — 代码全面"现代化"
蜗牛往上爬 · 前端工业可视化学习笔记 第 12 周总结
本周把 ES6 最常用的三大语法(箭头函数、模板字符串、展开运算符)和一批便捷方法全部拿下。你的代码已经从"能跑"变成"现代、简洁、专业"。
目录
一、本周学了什么
知识图谱
函数与字符串/数组扩展
├── 箭头函数 =>
│ ├── 简化:省略 {} 和 return、单参省略括号
│ ├── this:继承外层(解决 this 丢失)
│ ├── 限制:不能 new、没有 arguments
│ └── 默认参数:(name = "默认")
│
├── 字符串扩展
│ ├── 模板字符串 ``:多行、表达式、嵌套
│ ├── includes / startsWith / endsWith
│ ├── repeat:进度条
│ └── padStart / padEnd:编号补零
│
└── 数组扩展
├── 展开 ...:合并、复制、传参、对象展开
├── find / findIndex:按条件查找
├── Array.from:类数组→真数组、生成序列
├── Array.of
├── includes(数组版)
├── flat / flatMap:拍平嵌套
└── sort:必须传比较函数、会改原数组
二、核心知识速记
三条铁律
回调用箭头函数,对象方法/构造函数用普通函数
sort 会改原数组——排序前用
[...arr]复制模板字符串渲染 HTML:
map(d => \${…}
`).join(“”)`
高频写法
// 箭头 + 解构 + 模板字符串(现代前端标配)
const onlineIds = deviceList
.filter(({ online }) => online)
.map(({ id }) => id);
// 合并对象并覆盖
const config = { ...base, temp: 85 };
// 按条件查找更新
const d = list.find(item => item.id === id);
if (d) d.temp = 50;
// 生成卡片 HTML
container.innerHTML = data
.map(d => `<div class="card">${d.name} ${d.temp}°C</div>`)
.join("");
// 生成序列
const months = Array.from({ length: 12 }, (_, i) => i + 1);
箭头函数 vs 普通函数(速查)
在工业可视化里的应用场景
三、本周踩过的坑
坑点 1:箭头函数返回对象忘了加括号
// ❌ {} 被当作函数体,返回 undefined
const getDevice = () => { id: "CNC-001" };
console.log(getDevice()); // undefined
// ✅ 加括号
const getDevice = () => ({ id: "CNC-001" });
console.log(getDevice()); // { id: "CNC-001" }
坑点 2:对象方法用箭头函数,this 丢失
// ❌ this 不是 obj(箭头函数没有自己的 this)
const device = {
name: "CNC-001",
show: () => console.log(this.name) // this 是外层(window)
};
device.show(); // undefined
// ✅ 对象方法用普通函数
const device = {
name: "CNC-001",
show: function () { console.log(this.name); }
};
device.show(); // "CNC-001"
坑点 3:sort 数字排序没传比较函数
// ❌ 默认按字符串排序
const nums = [3, 10, 1, 20];
console.log(nums.sort()); // [1, 10, 20, 3]
// ✅ 传比较函数
console.log(nums.sort((a, b) => a - b)); // [1, 3, 10, 20]
坑点 4:sort 修改了原数组
// ❌ 原数组被改了,后续统计出错
const sorted = deviceList.sort((a, b) => a.temp - b.temp);
console.log(deviceList); // 顺序已经变了!
// ✅ 先复制再排序
const sorted = [...deviceList].sort((a, b) => a.temp - b.temp);
坑点 5:模板字符串里忘了嵌套的引号
// ❌ 生成 HTML 时字符串里又用双引号,转义混乱
const html = `<div class="card" data-status="运行中">`; // 正常 ✅
// ❌ 模板里拼 class 条件时要小心
const html = data.map(d =>
`<div class="card ${d.temp > 50 ? "hot" : ""}">${d.temp}</div>`
).join(""); // ✅ 单双引号分开,正常
四、自测清单
[ ] 箭头函数省略 {} 和 return 的条件?
[ ] 箭头函数返回对象为什么要加括号?
[ ] 箭头函数的 this 和普通函数有什么不同?
[ ] 箭头函数能 new 吗?有 arguments 吗?
[ ] 对象方法应该用哪种函数?
[ ] 模板字符串和 + 拼接相比的优势?
[ ] 如何用模板字符串生成列表 HTML?
[ ] includes 和 indexOf 判断存在哪个更直观?
[ ] padStart 是干嘛的?举一个使用场景
[ ] 展开运算符和解构的区别?
[ ] 如何复制数组且不影响原数组?
[ ] find 和 findIndex 找不到分别返回什么?
[ ] Array.from 的两个常见用途?
[ ] flat 和 flatMap 的区别?
[ ] sort 为什么必须传比较函数?如何避免改原数组?
五、下周预告
第 13 周:对象扩展与 Set/Map
下周的 Set/Map 是 ES6 新增的数据结构——Set 天然去重,Map 比对象更适合存储键值数据。
🚀 第 12 周完成!你的代码已经"现代化"。下周学习对象扩展和 Set/Map,数据结构的工具箱继续升级!