python版的:
a, (b, [c, d]) = (1, [2, iter((3, 4))])
print(a, b, c, d)
head, *tail=(1,2,3)
print(head,tail)
js版的:
let [a, [b, [c, d]]] = [1, [2, [3, 4]]];
console.log(a, b, c, d);
let [head, ...tail]=[1,2,3];
console.log(head,tail);
输出都是:
1 2 3 4
1 [ 2, 3 ]
没感觉python有多么屌啊。
Array destructuring
let [one, two, three] = ['one', 'two', 'three'];//一般的
let [a=5, b=7] = [1];//默认值
[a, b] = [b, a];//交换a,b的值
[a,,,b]=[1,2,3,4];//a是1,b是4,一个逗号忽略一个值
[a, ...b] = [1, 2, 3];//a是1,b是[2,3]
Object destructuring
({a, b} = {a: 1, b: 2});
//or
let {a, b} = {a: 1, b: 2};
不能直接写{a, b} = {a: 1, b: 2},因为这样的话{a,b}会被当作一个块(block)而非对象字面量
//变量名字和属性名字不一样,并且设置默认值
let {a:aa = 10, b:bb = 5} = {a: 3};
console.log(aa); // 3
console.log(bb); // 5
let {a, ...rest} = {a: 10, b: 20, c: 30, d: 40}
console.log(a,rest);//10 { b: 20, c: 30, d: 40 }
const { 'fizz-buzz': fizzBuzz } = { 'fizz-buzz': true };
console.log(fizzBuzz); // "true"
参考文献: