JavaScript解构赋值是从数组或对象中提取值并赋给变量的简洁语法,支持对象/数组解构、重命名、默认值、嵌套、剩余参数及函数参数解构,大幅提升代码可读性与开发效率。
JavaScript解构赋值是一种从数组或对象中提取值并赋给变量的简洁语法,它让取值操作更直观、代码更少、可读性更高。
不用再写 const name = user.name; const age = user.age; 这样重复的点号访问。只要结构匹配,就能一次性把多个属性赋给同名变量:
const { name, age } = user; —— 变量名必须和属性名一致const { name: userName, age: userAge } = user; —— 冒号左边是原属性名,右边是新变量名const { city = 'Beijing', avatar } = user; —— 当 city 为 undefined 时启用默认值const { profile: { bio, tags } } = user; —— 直接深入一层或多层取值,无需先取 profile
告别 const first = arr[0]; const second = arr[1];,用方括号按索引顺序快速取值:
const [a, b, c] = [1, 2, 3]; —— a=1, b=2, c=3
const [first, , third] = ['a', 'b', 'c']; —— 中间留空,first='a', third='c'
const [head, ...tail] = [1, 2, 3, 4]; —— tail 是数组 [2, 3, 4]
[x, y] = [y, x]; —— 一行完成交换把解构用在函数形参上,能直接“拆开”传入的对象或数组,省去函数体内手动提取的步骤:
function greet({ name, greeting = 'Hello' }) { return `${greeting}, ${na
me}!`; }greet({ name: 'Alice' }),不用关心参数顺序function sum([a, b]) { return a + b; }sum([3, 5]) 即得 8
function createPost({ title, content, tags = [], published = false }) { ... } —— 参数语义明确,缺省安全常见开发中,解构能显著减少样板代码:
const { data: { id, username }, status } = await fetchUser();
function Button({ size = 'md', variant = 'primary', children }) { ... }
const [userRes, postRes] = await Promise.all([fetchUser(), fetchPosts()]);
input.addEventListener('input', ({ target: { value } }) => console.log(value));