一、ES6简介?
ES6是 JavaScript 语⾔的下⼀代标准,在 2015 年 6 ⽉正式发布。它的⽬标,是使得
JavaScript 语⾔可以⽤来编写复杂的⼤型应⽤程序,成为企业级开发语⾔。
nodejs对ES6的⽀持很⾼,⽬前多数浏览器也对ES6进⾏了⽀持,不过我们在企业级开发中
仍需要通过Babel将ES6的⾼级语法转换为ES5,这样使得我们的程序兼容性更强。
二、变量声明
在ES5中,我们通过var来声明变量,这个关键字有点特殊,其声明的变量没有局部作⽤域,存在变量声明的提升,并且可以对⼀个变量进⾏重复声明,这种语法特点显得很不规范。
1.let
let声明的变量具有如下特点:
- 具有局部作用域
- 不存在变量声明提升
- 不可以对一个变量进行重复声明
- 存在暂时性死区
//具有局部作用域
{
let a = 10
var b = 20
}
console.log(a); // a is not defined
console.log(b); // 20
//不存在变量声明提升
// var 的情况
console.log(num1); // 输出undefined
var num1 = 10;
// let 的情况
console.log(num2); // 报错ReferenceError
let num2 = 20;
//不可以对一个变量进行重复声明
// 报错
function func() {
let a = 10;
var a = 1;
}
// 报错
function func() {
let a = 10;
let a = 1;
}
//存在暂时性死区
var tmp = 123;
if (true) {
tmp = 'abc'; // ReferenceError
let tmp;
}
2、const
const⽤于声明⼀个常量,⼀旦声明,常量的值就不能改变。此外,const具有let的所有特
点。
const PI = 3.1415;
console.log(PI);// 3.1415
PI = 3;
console.log(PI);
// TypeError: Assignment to constant variable.
三、解构
ES6 允许按照⼀定模式,从数组和对象中提取值,对变量进⾏赋值,这被称为解构。解构
的本质是模式匹配,也就是说只要等号两边的模式相同,左边的变量就会被赋予对应的值。解构时如果解构不成功,变量的值就等于 undefined 。
1、对象解构
通过⼤括号来匹配等号右边的对象。
let { name, age, add } = { name: 'tom', age: 12, add: function () { console.log('我是一个方法'); } }
add()
console.log(name, age)
//我是一个方法
//tom 12
let { foo, bar } = { foo: 'aaa', bar: 'bbb' };
console.log(foo,bar); //aaa bbb
let {foo} = {bar: 'baz'};
console.log(foo); //undefined
2、数组的解构
通过中括号来匹配等号右边的数组值。对于 Set 结构,也可以使⽤数组的解构赋值。
let [foo, [[bar], baz]] = [1, [[2], 3]];
console.log(foo,bar,baz); //1 2 3
let [head, ...tail] = [1, 2, 3, 4];
console.log(head,tail); //1 [ 2, 3, 4 ]
let [x, y, ...z] = ['a'];
console.log(x,y,z); //a undefined []
let [a, [b], d] = [1, [2,3], 4]; // 不完全解构
console.log(a,b,d); //1 2 4
let [x, y, z] = new Set(['a', 'b', 'c']); //解构set集合
console.log(x,y,z); // a b c
let [x, y = 'b'] = ['a', undefined];
console.log(x,y); //a b