1. 什么是ES6
ES6是javascript的语法规范,由ECMA制定,ECMA即欧洲计算机协会,其中的数字6为版本号。
2. ES6新特性
2.1 变量
let 定义变量作用域,仅let所在的代码块。
var 定义全局变量。
function ab(b){
if(b){
{
let histr="Just do it!"
}
//报错,histr未定义
console.log(histr)
}
2.2 常量
const name='张三';
2.3 模板字符串
let name='lisi';
console.log(`你好${name},欢迎你!`);
解决长语名显示问题
2.4 默认参数
function act(num=250){
console.log(num);
}
//显示250
act();
//显示500
act(500);
2.5 箭头函数
特点:
1、不需要function关键字来创建函数
2、省略return关键字
3、继承当前的上下文this关键字
ES5函数原写法:
function add(a,b){
return a+b;
}
或:
add=function(a,b){
return a+b;
}
console.log(add(250,250));
//ES6写法:
add=(a,b)=>{
return a+b;
}
console.log(add(250,250));
如果{}只有一行,可以进一步简写为:
add=(a,b)=> a+b;
console.log(add(250,250));
2.6 对象初始化简写
ES5可能出现键值同名
funcion student(name,age){
return{
name:name,
age:age
};
}
ES6可简写为:
funcion student(name,age){
return{
name,
age
};
}
console.log(JSON.stringify(stduent('abc',12)));
2.7 解构
const student={
name:'zhangsan',
age:18
}
//ES5写法
const name=student.name;
const age=student.age;
//ES6写法
const {name,age}=student;
console.log(name);
console.log(age);
2.7 展开操作符
Spread Operator …三个点操作符
//数组
const job=['teacher','student'];
const jobs=[...job,'driver','doctor'];
console.log(jobs);
//对象
const alp={first:'a',second:'b'};
const alphabets={...alp,third:'c',fourth:'d'};
console.log(alphabets);
输出结果:
[ 'teacher', 'student', 'driver', 'doctor' ]
{ first: 'a', second: 'b', third: 'c', fourth: 'd' }
2.8 导入导出
//lib.js
let fn0=function(){
console.log('fn0');
}
export {fn0}
//demo.js
import {fn0} from './lib'
fn0();