Destructuring Assignment 非常灵活,跟 Spread 操作符可以结合起来,跟 Arrow Function 也可以结合起来:
var fun = ({a, b}) => a+b;
fun({a: 1, b: 2}) // 3
fun({a: 1}) // NaN (1+undefined)
// 甚至可以带默认参数
var fun2 = ({a, b} = {a: 1, b: 3}) => a+b;
fun2(); // 4
Array Destructuring
let input = [1, 2];
let [first, second] = input;
console.log(first); // outputs 1
console.log(second); // outputs 2
// swap variables
[first, second] = [second, first];
let [first, ...rest] = [1, 2, 3, 4];
console.log(first); // outputs 1
console.log(rest); // outputs [ 2, 3, 4 ]
// ignore trailing elements
let [first] = [1, 2, 3, 4];
console.log(first); // outputs 1
// ignore some elements
let [, second, , fourth] = [1, 2, 3, 4];
console.log(second); // outputs 2
console.log(fourth); // outputs 4
Object destructuring
let o = {
a: "foo",
b: 12,
c: "bar"
};
let { a, b } = o;
// surround with parentheses or JavaScript parses a `{` as the start of block
({ a, b } = { a: "baz", b: 101 });
// passthrough
let { a, ...passthrough } = o;
let total = passthrough.b + passthrough.c.length;
function f({ a, b = 4 } = { a: "hello" }) {
console.log(a, b)
}
f() // hello 4
f({a: 'world'}) // world 4
f({a: 'world', b: 2}) // world 2
TypeScript destructuring
看 TypeScript 官方的 handbook。与 JavaScript 基本一致。