JavaScript ES6新特性:箭头函数与解构赋值详解
·
JavaScript ES6新特性:箭头函数与解构赋值详解
一、箭头函数(Arrow Functions)
核心特性:
-
简洁语法
- 传统函数:
function(a, b) { return a + b; } - 箭头函数:
(a, b) => a + b - 单参数可省略括号:
x => x * 2 - 无参数需空括号:
() => console.log("Hello")
- 传统函数:
-
this绑定机制- 箭头函数不创建自身
this,而是继承外层作用域的this值 - 解决传统函数中
this指向问题:// ES5问题 const obj = { count: 0, increment: function() { setInterval(function() { console.log(this.count++); // this指向window }, 1000); } }; // ES6解决方案 const obj = { count: 0, increment: function() { setInterval(() => { console.log(this.count++); // this正确指向obj }, 1000); } };
- 箭头函数不创建自身
-
不适用的场景
- 不能作为构造函数(无
prototype属性) - 不能使用
arguments对象(需用剩余参数...args替代) - 不适合对象方法(需要自身
this时)
- 不能作为构造函数(无
二、解构赋值(Destructuring Assignment)
1. 数组解构
// 基础解构
const [a, b] = [1, 2]; // a=1, b=2
// 默认值
const [x=10, y] = [undefined, 20]; // x=10, y=20
// 嵌套解构
const [p, [q, r]] = [1, [2, 3]]; // p=1, q=2, r=3
// 跳过元素
const [first, , third] = [10, 20, 30]; // first=10, third=30
2. 对象解构
// 基础解构
const { name, age } = { name: "Alice", age: 30 };
// 重命名变量
const { width: w, height: h } = { width: 100, height: 200 };
// 嵌套解构
const {
address: { city, street }
} = {
address: { city: "Beijing", street: "Chaoyang" }
};
// 函数参数解构
function getUser({ id, name }) {
console.log(`ID: ${id}, Name: ${name}`);
}
getUser({ id: 101, name: "Bob" });
3. 数学计算中的应用
解构可简化数学运算:
// 交换变量(无需临时变量)
let m = 5, n = 8;
[m, n] = [n, m]; // m=8, n=5
// 函数返回多个值
function calc(a, b) {
return [a+b, a*b, a-b];
}
const [sum, product, diff] = calc(3, 4); // sum=7, product=12, diff=-1
三、联合使用案例
// 箭头函数 + 解构
const users = [
{ id: 1, name: "Tom" },
{ id: 2, name: "Jerry" }
];
// 提取id数组
const ids = users.map(({ id }) => id); // [1, 2]
// 解构函数参数
const printUser = ({ name, id }) =>
console.log(`${name} (ID: ${id})`);
users.forEach(printUser);
// 输出: Tom (ID: 1)
// Jerry (ID: 2)
关键优势:
- 箭头函数:减少代码量,避免
this陷阱- 解构赋值:提升数据提取效率,支持复杂嵌套结构
二者结合显著提升代码可读性和开发效率。
更多推荐

所有评论(0)