ES6规定,允许按照一定模式从数组和对象中提取值,对变量进行赋值,这种被称为解构。
一、 数组的解构赋值
数组的解构赋值是指,左边是一个数组,右边也是数组,按照对应的位置对左边的变量进行赋值。
let [a, [b], c] = [1, [2,3], 4];
//a=1, b=2, c=4
如果结构不成功,变量的值就等于undefined。
let [x, y, ...z]=['a'];
//x='a', y=undefined, c=[]
如果等号右边的值或转为对象以后,不具备Interator接口,或者本身不具备Interator接口,则会报错。
let [a] = 1;
let [a] = false;
let [a] = NaN;
let [a] = undefined;
let [a] = null;
let [a] = {};
// 以上都会报错,前面五个转为对象后不具备Interator接口,最后一个本身不具备Interator接口
解构赋值允许指定默认值(备注:变量对应位置的值必须===undefined才能生效):
let [a = true] = [1];
//a=true
let [x, y='b'] = ['a'];
//x='a', y='b'
let[c=true]= [null];
//c=null,以为c对应位置的值为null,null!==undefined,故默认值无效
二、对象的解构赋值
变量必须与属性同名,才能取到对应的值:
let {a, b} = {a:1, b:2};
//a=1, b=2
let {c} = {a:1, b:2};
//c=undefined
参考文章:http://es6.ruanyifeng.com/