🔥 ES6+ 核心语法糖全解析:让代码优雅 10 倍!(面试必考)
前言:2015 年 ES6 发布是 JavaScript 的分水岭!之前 JS 变量提升混乱、面向对象困难;之后融合多语言长处,代码优雅简洁。本文带你彻底搞懂 解构、Rest、模板字符串、BigInt 等 8 大核心特性,文末附完整代码模板!
📋 目录
1. 解构赋值(数组/对象/嵌套/字符串)
2. Rest 运算符
3. 对象简写语法
4. 模板字符串
5. for...of 循环
6. BigInt 大整数
7. 指数运算符
8. 函数默认参数
9. 其他 ES6+ 特性
10. 面试高频题
1️⃣ 解构赋值:从数组/对象中快速提取数据
核心概念
解构赋值 = 从数组或对象中快速提取数据,赋值给变量
// ❌ ES5 传统写法
let a = 1, b = 2, c = 3;
// ✅ ES6 解构写法
let [a, b, c] = [1, 2, 3];
数组解构
// 基础解构
const [a, b, c] = [1, 2, 3];
console.log(a, b, c); // 1, 2, 3
// 跳过某些值
const [first, , third] = [1, 2, 3];
console.log(first, third); // 1, 3
// 交换变量(经典应用)
let x = 1, y = 2;
[x, y] = [y, x];
console.log(x, y); // 2, 1
嵌套数组解构
const arr = [1, [2, 3, [4], 5]];
const [a, [b, c, [d], e]] = arr;
console.log(a, b, c, d, e); // 1, 2, 3, 4, 5
字符串解构
// 字符串可解构为字符数组
const [a, b, c, d, e] = 'hello';
console.log(a, b, c, d, e); // 'h', 'e', 'l', 'l', 'o'
// 解构字符串属性
const { length } = 'hello';
console.log(length); // 5(字符串包装类的属性)
对象解构
const obj = {
name: '张三',
age: 18,
sex: '男',
like: {
sport: '篮球'
}
};
// 基础解构
const { name, age } = obj;
console.log(name, age); // '张三', 18
// 嵌套解构
const { name, like: { sport } } = obj;
console.log(name, sport); // '张三', '篮球'
// 重命名变量
const { name: userName, age: userAge } = obj;
console.log(userName, userAge); // '张三', 18
对象属性简写
const sex = '男';
const name = '张三';
// ❌ ES5 写法
const obj1 = {
name: name,
sex: sex
};
// ✅ ES6 简写(变量名=属性名时可省略)
const obj2 = {
name,
sex
};
2️⃣ Rest 运算符:收集剩余元素
数组 Rest
const arr = [1, 2, 3, 4, 5];
// 第一个元素 + 剩余数组
const [a, ...b] = arr;
console.log(a); // 1
console.log(b); // [2, 3, 4, 5]
// 实际应用场景
const users = ['张三', '李四', '王五'];
const [captain, ...players] = users;
console.log(captain); // '张三'(队长)
console.log(players); // ['李四', '王五'](队员)
对象 Rest
const { name, ...others } = {
name: '张三',
age: 18,
city: '北京'
};
console.log(name); // '张三'
console.log(others); // { age: 18, city: '北京' }
函数参数 Rest
// ❌ ES5 使用 arguments(类数组)
function foo() {
console.log(arguments); // [1, 2, 3, 4, 5]
console.log(typeof arguments); // 'object'
}
// ✅ ES6 使用 Rest 参数(真数组)
function foo(...args) {
console.log(args); // [1, 2, 3, 4, 5]
console.log(typeof args); // 'object'
console.log(Array.isArray(args)); // true
}
foo(1, 2, 3, 4, 5);
Rest vs Arguments 对比
| 特性 | arguments | Rest 参数 |
|---|---|---|
| 类型 | 类数组对象 | 真数组 |
| 可用数组方法 | ❌ | ✅ |
| 只能收集全部 | ✅ | ❌(可部分收集) |
| ES 版本 | ES3 | ES6 |
3️⃣ 模板字符串:字符串拼接的终极方案
基础用法
const myname = '张三';
// ❌ ES5 拼接
console.log('hello ' + myname);
console.log('hello ' + myname.toUpperCase());
// ✅ ES6 模板字符串
console.log(`hello ${myname}`);
console.log(`hello ${myname.toUpperCase()}`);
多行字符串
// ❌ ES5 多行需要拼接
const str1 = '第一行\n' +
'第二行\n' +
'第三行';
// ✅ ES6 直接换行
const str2 = `第一行
第二行
第三行`;
表达式插值
const a = 10, b = 20;
// 任意表达式都可以
console.log(`${a} + ${b} = ${a + b}`); // 10 + 20 = 30
console.log(`${a > b ? 'a 大' : 'b 大'}`); // b 大
标签模板(高级用法)
function tag(strings, ...values) {
console.log(strings); // ['hello ', '']
console.log(values); // ['张三']
return strings[0] + values[0].toUpperCase();
}
const result = tag`hello ${myname}`;
console.log(result); // hello 张三
4️⃣ for...of 循环:遍历的可迭代协议
基础用法
const arr = [1, 2, 3, 4, 5];
// ❌ for 循环(需要索引)
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
// ✅ for...of(语义更清晰)
for (const item of arr) {
console.log(item);
}
遍历各种数据结构
// 数组
for (const num of [1, 2, 3]) {
console.log(num);
}
// 字符串
for (const char of 'hello') {
console.log(char); // 'h', 'e', 'l', 'l', 'o'
}
// Map
const map = new Map([['name', '张三'], ['age', 18]]);
for (const [key, value] of map) {
console.log(key, value);
}
// Set
const set = new Set([1, 2, 3]);
for (const item of set) {
console.log(item);
}
for...in vs for...of
| 特性 | for...in | for...of |
|---|---|---|
| 遍历对象 | ✅ | ❌ |
| 遍历数组 | ⚠️(遍历索引) | ✅(遍历值) |
| 遍历字符串 | ⚠️ | ✅ |
| 遍历 Map/Set | ❌ | ✅ |
| 推荐场景 | 对象属性 | 可迭代对象 |
5️⃣ BigInt:解决大整数精度问题
为什么需要 BigInt?
// ❌ Number 精度限制
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991 (2^53 - 1)
console.log(9007199254740992 === 9007199254740993); // true ❌
// IEEE 754 双精度浮点数
// 64 位 = 1 位符号 + 11 位指数 + 52 位尾数
// 有效精度 = 53 位
BigInt 用法
// 创建 BigInt(后缀 n)
const num = 1234567893214561234564856n;
console.log(num, typeof num); // 1234567893214561234564856n, 'bigint'
// 运算
const a = 9007199254740993n;
const b = 1n;
console.log(a + b); // 9007199254740994n
// ⚠️ 不能与 Number 混用
// 9007199254740993n + 1; // ❌ TypeError
console.log(9007199254740993n + 1n); // ✅
实际应用场景
// 1. 后端大整数 ID(用户 ID、订单 ID)
const userId = '9007199254740993';
const bigId = BigInt(userId);
// 2. 金融计算(避免精度丢失)
const amount = 1000000000000000000n; // 精确计算
// 3. 密码学、加密算法
const prime = 2n ** 255n - 19n;
6️⃣ 指数运算符:更简洁的幂运算
// ❌ ES5 使用 Math.pow
console.log(Math.pow(2, 10)); // 1024
// ✅ ES7 指数运算符
console.log(2 ** 10); // 1024
console.log(2 ** 3 ** 2); // 512(右结合)
// 复合赋值
let num = 2;
num **= 3; // num = num ** 3 = 8
7️⃣ 函数默认参数:告别 undefined 判断
// ❌ ES5 需要手动判断
function foo(x, y) {
x = x || 3;
y = y || 4;
return x + y;
}
// ✅ ES6 默认参数
function foo(x = 3, y = 4) {
return x + y;
}
console.log(foo()); // 7
console.log(foo(1, 2)); // 3
console.log(foo(1)); // 5
console.log(foo(undefined, 2)); // 5
默认参数与解构结合
// 函数参数解构 + 默认值
function createUser({ name = 'Guest', age = 18 } = {}) {
console.log(name, age);
}
createUser(); // Guest, 18
createUser({ name: '张三' }); // 张三, 18
8️⃣ 其他 ES6+ 重要特性
箭头函数
// ❌ ES5
const add = function(a, b) {
return a + b;
};
// ✅ ES6 箭头函数
const add = (a, b) => a + b;
// 单参数可省略括号
const double = x => x * 2;
// 无参数需要空括号
const sayHi = () => console.log('Hi');
let/const 块级作用域
// ❌ var 函数作用域,会变量提升
var x = 1;
// ✅ let/const 块级作用域
let y = 2;
const PI = 3.14;
// 推荐:默认 const,需要变化用 let,避免 var
Class 类
// ❌ ES5 构造函数 + 原型
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function() {
console.log('Hello, ' + this.name);
};
// ✅ ES6 Class
class Person {
constructor(name) {
this.name = name;
}
sayHello() {
console.log(`Hello, ${this.name}`);
}
}
模块化
// export.js
export const name = '张三';
export function sayHi() {}
export default class User {}
// import.js
import User, { name, sayHi } from './export.js';
可选链 & 空值合并
// 可选链(ES2020)
const city = user?.address?.city;
// 空值合并(ES2020)
const name = userName ?? 'Guest';
9️⃣ ES6+ 特性速查表
| 特性 | ES 版本 | 用途 | 推荐使用 |
|---|---|---|---|
| 解构赋值 | ES6 | 快速提取数据 | ✅ |
| Rest 运算符 | ES6 | 收集剩余元素 | ✅ |
| 模板字符串 | ES6 | 字符串拼接 | ✅ |
| for...of | ES6 | 遍历可迭代对象 | ✅ |
| BigInt | ES2020 | 大整数精确表示 | ✅ |
| 指数运算符 | ES7 | 幂运算 | ✅ |
| 默认参数 | ES6 | 函数参数默认值 | ✅ |
| 箭头函数 | ES6 | 简洁函数语法 | ✅ |
| let/const | ES6 | 块级作用域 | ✅ |
| Class | ES6 | 面向对象 | ✅ |
| 模块化 | ES6 | 代码组织 | ✅ |
| 可选链 | ES2020 | 安全访问属性 | ✅ |
| 空值合并 | ES2020 | 默认值处理 | ✅ |
🔟 面试高频题
题1:解构赋值输出什么?
const [a, b] = [1, 2];
[b, a] = [a, b];
console.log(a, b);
题2:Rest 参数输出什么?
function foo(...args) {
console.log(Array.isArray(args));
}
foo(1, 2, 3);
题3:BigInt 相关
console.log(9007199254740992n === 9007199254740993n);
console.log(9007199254740992 === 9007199254740993);
题4:模板字符串输出什么?
const a = 1, b = 2;
console.log(`${a + b}`);
题5:默认参数陷阱
function foo(x = 1, y = 2) {
return x + y;
}
console.log(foo(undefined, 3));
📚 完整代码模板
// ============ ES6+ 语法糖模板 ============
// 1. 解构赋值
const [a, b, ...rest] = [1, 2, 3, 4, 5];
const { name, age, ...others } = user;
// 2. 模板字符串
const msg = `Hello, ${name}!`;
// 3. 箭头函数
const add = (a, b) => a + b;
// 4. 默认参数
function greet(name = 'Guest') {
return `Hello, ${name}`;
}
// 5. for...of
for (const item of array) {
console.log(item);
}
// 6. BigInt
const bigNum = 9007199254740993n;
// 7. 指数运算
const result = 2 ** 10;
// 8. 可选链 & 空值合并
const city = user?.address?.city;
const userName = name ?? 'Guest';
🎯 最佳实践建议
┌─────────────────────────────────────────────────────────────┐
│ ES6+ 编码规范建议 │
├─────────────────────────────────────────────────────────────┤
│ 1. 默认使用 const,需要变化用 let,避免 var │
│ 2. 优先使用解构赋值提取数据 │
│ 3. 字符串拼接用模板字符串 │
│ 4. 遍历用 for...of,对象用 for...in │
│ 5. 大整数用 BigInt 或字符串 │
│ 6. 函数参数用默认值 + Rest 参数 │
│ 7. 异步代码用 async/await │
│ 8. 安全访问用可选链,默认值用空值合并 │
└─────────────────────────────────────────────────────────────┘
📖 延伸学习
| 主题 | 推荐资源 |
|---|---|
| ES6 入门 | 阮一峰 ES6 教程 |
| Babel 转译 | Babel 官方文档 |
| 兼容性查询 | Can I Use |
| TypeScript | TS 官方文档 |
💬 互动话题
你最喜欢 ES6 的哪个特性?为什么?
欢迎在评论区分享你的看法,点赞最高的送 ES6 速查手册 PDF 一份!
觉得有用?请点赞 + 收藏 + 关注,下期预告:《Promise 异步编程详解:从回调地狱到 async/await》 🚀
本文参考了稀土掘金多篇高赞 ES6 文章,结合 2025-2026 年最新面试趋势整理而成。如有错误,欢迎指正!