es6之变量的解构赋值


1.基本用法(数组的解构)

let [a,b,c] = [1,2,3];
let [foo, [[bar],baz]] = [1,[[2],3]];
let [ , ,third] = ['foo','bar','baz'];
let [x, ,y] = [1,2,3];
let [head, ...tail] = [1,2,3,4];//tail=[2,3,4]
let [x,y,...z] = ['a'];//y=undefined,z=[]

解构不成功就等于undefined,

不完全解构,右边只匹配数组的一部分,也可以成功。但是如果是不可迭代的结构,解构就会报错。

// 不完全解构
let [x,y] = [1,2,3];
let [a,[b],d] = [1,[2,3],4];
// 报错
let [foo] = 1;
let [foo] = false;
let [foo] = NaN;

解构生成器函数

function* fibs(){
    let a=0;
    let b=1;
    while(true){
			yield a;
			[a,b]=[b,a+b];
    }
}
let [first,second,third,fourth,fifth,sixth] = fibs();
console.log(sixth);;//5

指定默认值

let [x=1] = [undefined];//x=1
let [y=1] = [null];//y=null

也可以引用解构赋值的其他变量

let [x1=1,y1=x] = [];
let [x2=1,y2=x2] = [2];
let [x3=1,y3=x3] = [1,2];//x3=1,y3=2

2.对象的解构

对象的解构是没有次序的

let {foo,bar}={bar:'b',foo:"a"};

将对象的方法赋值到某个变量

let {log} = console;
log('hello');

也可以这样写

let obj = {first:'hello', last:'world'};
let {first:f,last:l} = obj;
console.log(f,l);// hello world

实际上对象的解构是下面的简写

let { foo: foo, bar: bar } = { foo: 'aaa', bar: 'bbb' };

前面的是匹配的模式,后面的才是真正的变量,被赋值的也是后者

搞懂这个就能搞懂复杂一点的解构赋值

const node = {
  loc: {
    start: {
      line: 1,
      column: 5
    }
  }
};

let { loc, loc: { start }, loc: { start: { line }} } = node;
line // 1
loc  // Object {start: Object}
start // Object {line: 1, column: 5}

3.字符串的解构赋值

const [a, b, c, d, e] = 'hello';

4.数值和布尔值的解构赋值

let {toString: s} = 123;
s === Number.prototype.toString // true

let {toString: s} = true;
s === Boolean.prototype.toString // true

5.函数参数的解构赋值

[[1, 2], [3, 4]].map(([a, b]) => a + b);

当然也可以使用默认值。

一些解构常用用法:https://es6.ruanyifeng.com/#docs/destructuring

相关