变量解构是JavaScript中从数组或对象提取值并赋给变量的简洁语法,包括数组解构(按位置、跳过、默认值、剩余元素)、对象解构(按属性名、重命名、默认值、嵌套)、函数参数解构及交换变量等实用技巧。
变量解构是 J
avaScript 中一种从数组或对象中提取值并赋给变量的简洁语法,它让赋值更直观、代码更精简。
用方括号 [] 按索引顺序提取数组元素,跳过不需要的项,还能设置默认值。
const [a, b] = [1, 2]; → a=1,b=2const [, , c] = [1, 2, 3]; → c=3(忽略前两个)const [x = 10, y = 20] = [5]; → x=5,y=20const [first, ...rest] = [1, 2, 3, 4]; → first=1,rest=[2,3,4]用花括号 {} 按属性名提取对象中的值,支持重命名和默认值,不依赖顺序。
const { name, age } = { name: 'Alice', age: 30 };
const { name: fullName, age: years } = obj;
const { city = 'Beijing' } = { name: 'Bob' }; → city='Beijing'const { user: { id, profile: { email } } } = data;
在函数定义时直接对传入的数组或对象解构,避免函数体内重复取值。
function greet({ name, msg = 'Hello' }) { return `${msg}, ${name}!`; }
function sum([a, b]) { return a + b; }
function connect({ host = 'localhost', port = 3000 } = {}) { ... }
解构不只是“取值”,还能配合其他语法提升表达力。
[a, b] = [b, a];
function getCoords() { return [10, 20]; } const [x, y] = getCoords();
const newObj = { ...oldObj, name: 'New' };
基本上就这些。掌握解构能让你少写很多重复的点号和中括号,代码更干净,逻辑也更聚焦在业务本身上。