关键词:解构赋值
我们之前声明变量怎么声明?
var a = 10;
var b = 20;
var c = 30;
//或者
var a = 10,b = 20,c = 30;
//或者
var arr = [1,2,3,4,5];
var a = arr[0];
var b = arr[1];
var c = arr[3];
//或者
var obj = {
name: 'gary',
age: 20
}
var a = obj.name;
var b = obj.age;
这样如果声明太多变量会很麻烦,es6给我们提供了一种清新脱俗的方法:解构赋值
数组解构赋值
var [a,b,c] = ['美帝','阿三'];
console.log(a); //美帝
console.log(b); //阿三
es6还支持嵌套赋值
var [a,[[b,c],d]] = [1,[[2,3],4]];
console.log(a); //1
console.log(b); //2
console.log(c); //3
console.log(d); //4
不完全解构
//不完全解构,左边只是右边的一部分,但是模式是正确的
var [a,,c] = ['a1','b1','c1','d1'];
console.log(a); //a1
console.log(c); //c1
rest参数
var [a,...b] = ['a2','b2','c2','d2'];
//rest参数:作用与arguments类似,arguments是类数组
console.log(a); //a2
console.log(b); //['b2','c2','d2']
var [a,b,...c] = ['a3'];
//rest参数必须是最后一个元素
console.log(a); //a3
console.log(b); //undefined 解构不成功就是undefined
console.log(c); //[] rest参数解构不成功是空数组[]
字符串具有iterator接口
var [a,b,c] = 'hello';
console.log(a); //h
console.log(b); //e
console.log(c); //l
var [a,b,c] = new Set(['aa','bb','cc']);
console.log(a); //aa
console.log(b); //bb
console.log(c); //cc
对象解构赋值
对象的属性没有次序,变量必须与属性同名,才能取到正确的值,即变量名与属性名一一对应,次序不重要
var {foo,bar} = {bar: 'aaa', foo: 'bbb'}
console.log(bar); //aaa
console.log(foo); //bbb
var {foo} = {baz: 'ccc'}
console.log(foo); //undefined 因为变量与属性名不一致
var {baz:foo} = {baz: 'ddd'}
console.log(foo); //ddd foo指向baz属性对应的值
console.log(bar); // 报错
来个复杂点的
var obj = {p: ['风清扬',{y: '赵无极'}]}
var {p: [x,{y}]} = obj;
console.log(x); //风清扬
console.log(y); //赵无极
函数解构赋值
function f([x,y]){
return x+y;
}
console.log(f([1,2])); //3
function d({name = 'n',age = '2'} = {}){ //undefined会触发默认值
return `${name} ${age}`; //此处相当于name+' '+age
}
console.log(d()); //n 2
console.log(d({name: '张无梦',age: '120'})); //张无梦 120
默认值
var [a=1, b=2] = [,4];
console.log(a); //1 默认值
console.log(b); //4
var [a = 1, b = 2] = [4, undefined];
var [i = 10, s = 20] = [5,null];
console.log(a); //4
console.log(b); //2 默认值
console.log(i); //5
console.log(s); //null null !== undefined
//如果默认值是表达式,那么会进行惰性求值,即用到才会进行计算,用不到就不理它
function f(){
return '吕归尘';
}
var [a = f()] = [];
console.log(a) // 吕归尘
var [a = f()] = [2];
console.log(a) //2 f()不会执行
var {foo = 3} = {}
console.log(foo); //3
var {baz:foo = 3} = {baz: null}
console.log(foo); //null
var {baz:foo = 5} = {baz: undefined}
console.log(foo); //5
例子
1.求最大值
//正常方法
var arr = [2,5,1,8,4,2];
console.log(Math.max.apply(this, arr)); //8
//简化
var {max} = Math;
console.log(max.apply(this, arr)); //8
// 即是将现有方法赋值到变量上使用
2.交换变量
//正常
var a = 10;
var b = 20;
var c;
c = a;
a = b;
b = c;
console.log(a); //20
console.log(b); //10
//使用解构赋值
var x = 10;
var y = 20;
[x,y] = [y,x];
console.log(x); //20
console.log(y); //10
其他用法
- 从函数返回多个值
- 函数参数的定义
函数的参数如果是对象的成员,优先使用解构赋值 - 提取JSON数据
- 函数参数的默认值,在参数中指定默认值,避免 var a = obj || {}的语句
- 遍历Map解构
- 输入模块的指定方法
网友评论