解构赋值的优雅操作

43 阅读1分钟

解构赋值的优雅操作

什么是解构赋值

解构赋值是ES6的一个新语法,允许从数组或对象中提取数据,并赋值给变量。那么什么样的数据符合解构语法呢?

数组解构

任何可迭代对象(Iterable)均可使用数组解构

const [a, b] = [1, 2];          // 数组
const [c, d] = "hi";            // 字符串(可迭代)
const [e, f] = new Set([3, 4]); // Set(可迭代)
const [g, h] = arguments;       // arguments 对象

实现底层:底层依赖于迭代器协议

// 数组解构实际上调用迭代器
const [x, y] = [1, 2];
// 等价于:
const iter = [1, 2][Symbol.iterator]();
const x = iter.next().value;
const y = iter.next().value;
对象解构

必须是对象,包括包装后的对象。null/undefined会报错

const { name, age } = { name: "Alice", age: 30 }; // 普通对象
const { length } = "hello";                       // 字符串对象(包装后)
const { 0: x, 1: y } = [10, 20];                 // 数组(特殊键名)

实现底层:底层基于属性描述符查找

const obj = { a: 1, b: 2 };
const { a, b } = obj;
// 等价于查找 Object.getOwnPropertyDescriptor(obj, 'a')
嵌套解构

支持嵌套结构的数组或对象

// 嵌套数组
const [a, [b, c]] = [1, [2, 3]];

// 嵌套对象
const { user: { id, profile: { email } } } = {
  user: { id: 1, profile: { email: "a@b.com" } }
};
默认值

当解构值为undefined时,可设置默认值

const [a = 1] = [];           // a = 1
const { b = 2 } = { b: null }; // b = null(默认值不生效)