ES6解构用法

文章类型:Javascript

发布者:hp

发布时间:2025-04-15

一:引言

解构是ES6的的重要特性之一,用于从JavaScript对象和数组中提取数据,语法上比ES5所提供的更加简洁、紧凑、清晰。掌握好它不仅能让代码更简洁,还能大大提高开发效率

二:基础用法

1:数组基础结构

// 基础解构
const [first, second] = [1, 2, 3];
console.log(first);  // 1
console.log(second); // 2

// 跳过元素
const [, , third] = [1, 2, 3];
console.log(third);  // 3

2:对象结构重命名

const person = {
  name: '张三',
  age: 25
};

const { name: userName, age: userAge } = person;
console.log(userName); // '张三'
console.log(userAge);  // 25

3:设置默认值

// 数组默认值
const [x = 1, y = 2] = [undefined, null];
console.log(x); // 1
console.log(y); // null

// 对象默认值
const { title = '默认标题', count = 0 } = {};
console.log(title); // '默认标题'
console.log(count); // 0

4:嵌套解构

const user = {
  id: 1,
  info: {
    name: '李四',
    address: {
      city: '北京'
    }
  }
};

const { info: { name, address: { city } } } = user;
console.log(name); // '李四'
console.log(city); // '北京'

5:结合扩展运算符

// 数组结合扩展运算符
const [head, ...tail] = [1,2,3,4];
console.log(head); // 1
console.log(tail); // [2,3,4]
// 对象结合扩展运算符
const {id, ...rest} = {id:1, name:'李四', age: 35}
console.log(id); // 1
console.log(rest); // {name:'李四', age: 35}

6:函数参数解构

// 对象参数解构
function user({name, age = 35}){
    console.log(`${name}今年${age}岁`)
}
user({name:'李四'}) // "李四今年35岁"
//数组参数解构
function sum([a,b] = [0,0]){
    return a + b;
}
console.log(sum([1,3])) // 4

7:动态属性解构

const key = 'name';
const { [key]: value } = { name: '李四' }
console.log(value) // '李四'

8:解构用于交换变量

let a = 1, b = 2;
[a, b] = [b, a];
console.log(a) // 2
console.log(b) // 1

9:链式解构赋值

const obj = { a: 1, b: 2 };
const arr = [3, 4];
const { a, b } = obj, [c, d] = arr;

10:解构配合正则匹配

const [,year, month, day] = /(\d{4})-(\d{2})-(\d{2})/.exec('2025-02-26');
console.log(year, month, day) // 2025 02 26

11:解构导入模块

// 只导入需要的方法
import { useStste,useEffect } from 'react';
// 重命名导入
import { useStste as useStsteHook } from 'react';

12:条件解构

const data = null;
const { value = 'default' } = data ?? {};
console.log(value); // 'default'

13:安全解构

const safeObj = maybeNull || {}; 
const { value } = safeObj;

14:字符串解构

const [a, b] = 'ES6'; // a='E', b='S'

15:默认值触发条件

const { status = 'pending' } = { status: null }; // null
const { status = 'pending' } = { status: undefined }; // 'pending'

三:高阶用法

1:Map结构结构

const map = new Map([['react', 18], ['vue', 3]]);
for (const [lib, version] of map) {
    console.log(`${lib}@${version}`) 
}
// react@18
// vue@3

2:生成器YieId解构

function* dataStream() { 
    yield [1, { val: '2025' }] 
} 
const [[index, { val }]] = dataStream(); // index=1, val='2025'

3:Web API响应解构

const { 
    headers: { 'x-2025-version': apiVersion }, 
    body: { results: [firstItem] } 
} = await fetch('/2025-api').then(r => r.json());

4:ArrayBuffer解构

const buffer = new Uint8Array([72, 101]); 
const [firstByte, secondByte] = buffer; // 72, 101 → 'He'

5:防御性解构

// 可选链保护 
const { 
    user?.?.profile: { 
        email = 'default@2025.com' 
    } = {} 
} = serverResponse ?? {}; 
// 异常捕获模式 
try { 
    const { data } = JSON.parse(apiResponse);
} catch { 
    const { data } = { data: 'Fallback 2025 Data' }; 
}

6:柯里化参数解构

const createRequest = ({ headers }) => ({ body }) => fetch('/api', { headers, body });

7:管道式解构

const parseUser = ([, { name, age }]) => ({ name, birthYear: 2025 - age }); 
parseUser(['header', { name: 'Bob', age: 30 }]) // → {name: 'Bob', birthYear: 1995}

8:Proxy 拦截解构

const reactiveObj = new Proxy({ x: 10 }, { 
    get(t, p) { return t[p] * 2 } // 解构时会触发计算 
}); 
const { x } = reactiveObj; // x = 20

9:递归保护解构

const safeGet = (obj, path) => { 
    try { 
        return Function( 
            'o', 
            `return o?.${path.join('?.')}`
        )(obj); 
    } catch { 
        const [firstKey] = path; 
        return { [firstKey]: null }; 
    } 
};

四:总结

1:在解构时候不推荐使用var来进行,因为var声明的是全局变量,防止造成歧义;

2:解构时候变量名不能重复,不能对已经声明的变量名进行解构,否则会Error;

3:如果非得要对已经声明的变量进行解构,采用圆括号()把整个解构赋值括起来,

4:对数组进行解构的时候使用的是小括号[],因为数组是根据索引来进行取值的,

5::对对象进行解构采用的是花括号{},因为在对象中我们使用的是键值对(key:value)来进行取值的,