参考
Array Destructuring Assignment
old school
const items = [1, 2, 3]; const item1 = items[0]; const item2 = items[1]; const item3 = items[2];
一个一个从 array 拿出来, 再一个一个 assign 给每一个变量.
modern
const [item1, item2, item3] = [1, 2, 3];
一行里面做了 declare, assign, read from array. 3 个动作一气呵成.
get someone
const [, , value3] = [1, 2, 3];
with default value
const [v1] = []; // v1 = undefined const [v1 = 'default value'] = []; // v1 = 'default value' const [v1 = 'default value'] = ['value']; // v1 = 'value'
Object Destructuring Assignment
它和 Array 的用法差不多
const person = { name: 'Derrick', age: 11 };
const { name, age } = person;
with alias 别名
const person = { name: 'Derrick', age: 11 }; const { name: newName, age: newAge } = person; console.log(newName); console.log(newAge);
name: newName 中间使用了分号
with default value
const { name = 'Derrick', age } = {}; // name = 'Derrick' // age = undefined
nested
解构支持嵌套哦,
document.dispatchEvent( new CustomEvent('myevent', { detail: { tabName: 'tab name', }, }) );
监听时解构获取 tabName
document.addEventListener('myevent', ({ detail: { tabName } }) => { // do something... });
Common Use Case
上面的例子解构以后都被赋值到变量, 这个是最 common 的用法.
但其实你要 assign 到哪里都是可以的哦.
assign to parameters
function method1([v1, v2]) { console.log(v1); console.log(v2); } method1(['value1', 'value2']); function method2({ name, age }) { console.log(name); console.log(age); } method2({ name: 'Derrick', age: 11 });
assign to existing variables (swap value)
let v1 = 1; let v2 = 2; [v1, v2] = [v2, v1]; console.log(v1); // 2 console.log(v2); // 1
Mix cost and let when using destructuring assignment
参考: stackoverflow – How to mix const and let when using object or array destructuring assignment in ES6?
在 C# 可以这样 mix 着写
在 JS 则不行, 如果是要 declare const 或 let 那么就必须全部都是一样的, 同理如果是要 assign to exsiting variables 必须全部都是 existing.
解决方案就是多写几个 destructuring assignment 咯.
const array = [1, 2, 3]; let existingValue = 1; [existingValue] = array; const [, value2] = array; let [, , value3] = array;
是不是有一种, 一个一个写更好的感觉...哈哈