解构赋值
ES6允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructing)。例如:let [a,b,c] = [1,2,3];
本质上,这种写法属于“模式匹配”,只要等号两边的模式相同,左边的变量就会被赋予对应的值。
如果结构不成功,变量的值就等于undefined。另一种情况是不完全解构,即等号左边的模式只匹配一部分的等号右边的数组。这种情况下,解构依然可以成功。
数组的解构赋值
let [a,b,c] = [1,2,3];
//不完全解构
let [a,[b],d] = [1,[2,3],4];//a = 1; b = 2; d = 4
//集合解构
let[head,...tail] = [1,2,3,4]; // head = 1;tail = [2,3,4]
//默认值(当匹配值严格等于undefined时,默认值生效);
let [x, y ='b'] = ['a'];//x = 'a',y = 'b'
//默认值也可以是函数;
function f(){console.log('aaa');}
let [x = f()] = [1];
对象的解构赋值
//对象的属性没有次序,变量必须与属性同名,才能取到正确的值
let {foo,bar} = {foo:'aaa',bar:'bbb'};//foo = 'aaa';bar = 'bbb'
//如果变量名与属性名不一致,必须是以下这样
var{foo:baz} = {foo:'aaa',bar:'bbb'};//baz = 'aaa';
//实际上,对象解构赋值是以下形式的简写
let {foo:foo,bar:bar} = {foo:'aaa',bar:'bbb'};
//嵌套解构
let obj = {p:['Hello',{y:'World'}]};
let {p:[x,{y}]} = obj;//x = 'Hello';y = 'World'
//默认值 生效的条件是,对象的属性值严格等于undefined
var {x:y = 3} = {};//y = 3
字符串的解构赋值
解构时,字符串被转换成了一个类似数组的对象
const [a,b,c,d,e] = 'hello' ;//a=h;b=e;c=l;d=l;e=o;
也可以对数组的属性解构
let{length : len } = 'hello';//len = 5
数值和布尔值的解构赋值
解构时,若等号的右边是数值或布尔值,则会先转为对象
let {toString:s} = 123;//s === Number.prototype/toString ture
let {toString:s} = ture;//s === Boolean.prototype.toString true
函数参数的解构赋值
基本语法
function add([x,y]){return x+y;}
add([1,2]);
默认值
function move({x=0,y=0}){
return [x,y];
}
move({x:3,y:8});//[3,8]
move({x:3});//[3,0]
move({});//[0,0]
move();//[0,0]
解构赋值的常见用途
-
交换变量的值
let x = 1; let y = 2; [x,y] = [y,x];
-
从函数返回多个值
function example(){ return [1,2,3; } let [a,b,c] = example();
-
函数参数的定义
function f([x,y,z]){...} f([1,2,3]);
-
提取JSON数据
let jsonData = {id:42,status:'OK',data:[867,5309]}; let {id,status,data:number} = jsonData;
-
输入模块的指定方法
const {SourceMapConsumer,SourceNode} = require('source-map');
-
函数参数的默认值
指定参数的默认值,就避免了在函数体内部再写
var foo = config.foo||'default foo';
这样的语句jQuery.ajax = function(url,{ async = ture,cache = true,global = true, beforeSend = function(){}, complete = function(){}, //...more config }){//...do stuff}
-
遍历map解构
var map = new Map(); map.set('first','hello'); map.set('second','world'); for(let [key,value] of map){ console.log(key + 'is' + value); }