ES6常用方法
下面给你一份ES6+ 常用方法与语法总结(偏实战 + 高频 API),重点覆盖你在 Vue / uniapp / 数据处理 中最常用的部分。
一、数组方法(ES6+核心🔥)
1. map(映射)
const arr = [1, 2, 3];
const res = arr.map((x) => x * 2);
// [2, 4, 6]
👉 场景:
- 提取字段
- 接口数据 → UI数据
2. filter(过滤)
const res = arr.filter((x) => x > 1);
3. find / findIndex
arr.find((x) => x === 2); // 找值
arr.findIndex((x) => x === 2); // 找索引
4. some / every
arr.some((x) => x > 2); // 是否存在
arr.every((x) => x > 0); // 是否全部满足
5. includes(ES6)
arr.includes(2);
6. Array.from(类数组 → 数组)
Array.from("123"); // ['1','2','3']
7. 展开运算符(非常重要🔥)
const arr = [1, 2];
const newArr = [...arr, 3];
👉 用途:
- 合并数组
- 拷贝数组
8. flat(数组扁平化)
[1, [2, [3]]].flat(Infinity);
9. reduce(进阶核心🔥)
const sum = [1, 2, 3].reduce((acc, cur) => acc + cur, 0);
👉 常见用途:
// 数组转对象
const obj = list.reduce((acc, item) => {
acc[item.id] = item;
return acc;
}, {});
二、对象方法
1. Object.keys / values / entries
Object.keys(obj);
Object.values(obj);
Object.entries(obj);
2. Object.assign
const newObj = Object.assign({}, obj1, obj2);
👉 等价于:
const newObj = { ...obj1, ...obj2 };
3. 对象展开(ES6🔥)
const obj = { a: 1, b: 2 };
const newObj = { ...obj, c: 3 };
4. 可选链(ES2020,但必须会🔥)
obj?.a?.b;
👉 解决:
- undefined 报错问题(你之前 v-if 那个场景)
5. 空值合并运算符(??)
const val = input ?? "默认值";
👉 区别:
||会把 0 / '' 当 false??只处理 null / undefined
三、解构赋值(超高频🔥)
1. 数组解构
const [a, b] = [1, 2];
2. 对象解构
const { name, age } = user;
3. 重命名
const { name: userName } = user;
4. 默认值
const { age = 18 } = user;
四、函数增强
1. 默认参数
function fn(a = 10) {
return a;
}
2. 剩余参数(...args)
function fn(...args) {
console.log(args);
}
3. 展开参数
fn(...arr);
五、Promise(异步核心🔥)
1. 基础用法
new Promise((resolve, reject) => {
resolve("成功");
});
2. then / catch
api()
.then((res) => {})
.catch((err) => {});
3. async / await(必须掌握🔥)
async function getData() {
const res = await api();
}
4. Promise.all
await Promise.all([api1(), api2()]);
👉 场景:
- 多接口并发
六、字符串增强
1. 模板字符串
const str = `姓名:${name}`;
2. includes / startsWith / endsWith
str.includes("a");
str.startsWith("a");
3. repeat
"a".repeat(3); // 'aaa'
七、Set / Map(进阶但实用🔥)
1. Set(去重)
const set = new Set([1, 2, 2]);
[...set]; // [1,2]
2. Map(比对象更强)
const map = new Map();
map.set("a", 1);
map.get("a");
八、你项目里最常用组合(重点🔥)
1. 接口 → UI
list.map((item) => ({
label: item.name,
value: item.id,
}));
2. 多选 → 提交
selected.map((item) => item.id);
3. 安全取值(避免报错)
data?.introduction?.scaleDesc || [];
4. 页面传参(你高频用)
const str = encodeURIComponent(JSON.stringify(obj));
const obj = JSON.parse(decodeURIComponent(str));
九、你这个阶段最该熟练的(结合你当前技术栈)
直接给你结论(优先级)👇
⭐ 必须熟练
map / filter / find...展开运算符解构赋值async / awaitoptional chaining (?.)
⭐ 进阶核心
reducePromise.allSet 去重
如果你要再进一层(很关键)
我可以帮你补一版:
👉 “Vue项目中 ES6 的真实业务用法(不是语法,是套路)”
比如:
- 表单回显(后端 → 前端)
- 多选回填
- 聊天流数据结构处理(你现在正在做的)
- router 复杂传参设计
直接说一声,我给你整理一版“能直接抄进项目”的。