解构赋值是ES6容许按照必定模式,从数组和对象中提取值,对变量进行赋值;数组
解构赋值主要有一下几种函数
let [a,b,c] = [1,2,3];
容许有默认值prototype
let [foo = true] = []; foo//true let [x,y='b'] = ['a']; //x='a';y='b';
对象的解构和数组不一样的地方是,数组的元素必须是按次序排列的,变量的值由它的位置决定;对象的属性是无序的,变量名与属性名相同就能够了。code
let {foo, bar} = {foo: 'aaa', bar: 'bbb'}; foo//'aaa' bar//'bbb'
若是变量名和属性名不一致,或者想要给这个变量名和属性名不同,能够这样使用。对象
var {foo: baz} = {foo: 'aaa', bar:'bbb'} bar//'aaa'
这至关于给给变量赋值,并且变量名不须要和属性名同样。接口
若是对一个已经声明的变量,须要谨慎ip
let x; {x} = {x: 1};//SyntaxError
由于Javascript引擎会将{x}理解成一个代码块,从而发生语法错误。字符串
({x} = {x:1})
let [a,b,c,d,e] = 'hello'; a//'h' b//'e'
相似数组的对象都有一个length属性,所以能够对这个属性解构赋值部署
let {length: len} = 'hello'; len//5
let {toString: s} = 123; s === Number.prototype.toString // true let {toString: s} = true; s === Boolean.prototype.toString // true
function add([x, y]){ return x + y; } add([1, 2]); // 3
ES6内部使用的是严格相等运算符(===),判断一个位置是否有值。若是一个组员不严格等于undefined,默认值是不会生效的。it
let [x=1] = [undefined]; x//1 let [x=1] = [null]; x//null let {x=3} = {x: undefined}; x//3 let {x=3} = {x:null}; x//null;
交换变量的值
let x = 1; let y = 2; [x, y] = [y, x];
从函数中返回多个值
// 返回一个数组
function example() { return [1, 2, 3]; } let [a, b, c] = example(); // 返回一个对象 function example() { return { foo: 1, bar: 2 }; } let { foo, bar } = example();
函数参数的赋值
提取JSON数据
函数参数的默认值。
指定了默认值,就能够避免在函数体内写var foo = foo || "init".
遍历Map结构。
任何部署了Iterator接口的对象,均可以用for...of循环遍历。