一、ES6合集之let 和const
二、ES6合集之解构赋值
三、ES6合集之Map和Set
参考菜鸟教程:https://www.runoob.com/w3cnote/es6-tutorial.html
此文章仅用于自己学习
ES6 数据类型除了 Number 、 String 、 Boolean 、 Object、 null 和 undefined ,还新增了 Symbol 。
1.ES6 解构赋值
解构赋值是对赋值运算符的扩展。
他是一种针对数组或者对象进行模式匹配,然后对其中的变量进行赋值。
解构的目标,解构赋值表达式的左边部分。-- 解构的源,解构赋值表达式的右边部分。
1.1数组模型的解构(Array)
基本解构
let [a, b, c] = [1, 2, "3"]
console.log(a, b, c);//1 2 '3'
可嵌套-解构
let [a, [b, [c]]] = [1, ['2', [3]]]
console.log(a, b, c);//1 '2' 3
可忽略
let [a, [, [c]]] = [1, ['2', [3]]]
console.log(a, c);//1 '2'
不完全解构
let [a, b, c] = [1, 2]
console.log(a, b, c);//1 2 undefined
let [a = 1, b] = []
console.log(a, b);//1 undefined
剩余运算符
let [a, ...b] = [1, {2:3},{2:3}];
console.log(a, b);//1 [{2:3},{2:3}]
let [a, ...b] = [1, 2, 3];
console.log(a, b);//1 [2, 3]
字符串等
在数组的解构中,解构的目标若为可遍历对象,皆可进行解构赋值。可遍历对象即实现 Iterator 接口的数据。
let [a, b, c, d, e] = 'hello';
console.log(a, b, c, d, e);//a, b, c, d, e
解构默认值
//当解构模式有匹配结果,且匹配结果是 undefined 时,会触发默认值作为返回结果。
let [a = 2] = [undefined];
console.log(a);//2
//当解构模式有匹配结果时,返回匹配值。
let [a = 2] = [3];
console.log(a); //3
//a和b匹配结果都是 undefined,(触发默认值)返回默认值:a=3 b=a=3
let [a = 3, b = a] = []; // a = 3, b = 3
console.log(a, b);//3 3
//a正常解构赋值,a=1 ;b匹配结果都是 undefined,(触发默认值)返回b = a = 1
let [a = 3, b = a] = [1];
console.log(a, b);//1 1
//a和b正常解构赋值 a=1,b=2
let [a = 3, b = a] = [1, 2];
console.log(a, b);//1 2
用于值交换
// ES6 之前
let a = 1;
let b = 2;
let tmp;
tmp = a;
a = b;
b = tmp;
console.log(a, b);//2,1
//ES6之后
let a = 1;
let b = 2;
[a, b] = [b, a]
console.log(a, b);//2,1
1.2 对象模型的解构(Object)
let {foo,bar}={foo:'aaa',bar:'bbb'}
console.log(foo,bar);//aaa bbb
let {foo:bar}={foo:'aaa'}
console.log(bar);//aaa
可嵌套
let {p: [x, { y }] } = {p: ['hello', {y: 'world'}] };
console.log(x,y);//hello world
可忽略
let {p: [x, { }] } = {p: ['hello', {y: 'world'}] };
console.log(x);//hello
不完全解构
let {p: [{ x }, y ] } = {p: [{x: 'world1'}] };
console.log(x,y);//world1 undefined
剩余运算符
let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40};
console.log(a, b, rest);//10 20 {c: 30, d: 40}
解构默认值
let {a = 10, b = 5} = {a: 3};
console.log(a);//3
let {a: aa = 10, b: bb = 5} = {a: 3};
console.log(aa,bb);//3 5
let {a: aa = 10, b: bb = aa} = {a: 3};
console.log(aa,bb);//3 3