ES6新语法特性
1.使用let进行变量声明
function test() {
if (bool) {
let test = 'helloworld';
}
else {
//test 在此处访问不到
console.log(test);
}
}
2.常量的声明
const name = 'zhangsan';
name = 'lisi'; //再次赋值此时会报错
3.模版字符串
作用一:拼接字符串
//es5
var name = 'lux'
console.log('hello' + name)
//es6
const name = 'zhangsan'
console.log(`hello ${name}`) //hello zhangsan
作用二:多行字符串拼接
//es5
var msg = "Hi \
man!";
// es6
const template = `<div>
<span>hello world</span>
</div>`;
4.函数默认参数
//在定义函数时便初始化了这个参数,以便在参数没有被传递进去时使用
function action(num = 200) {
console.log(num);
}
action(); //200
action(300); //300
5.箭头函数
箭头函数特点:
- 不需要function关键字来创建函数
- 省略return关键字
- 继承当前上下文的 this 关键字
//es5
function test(num1,num2){
}
//es6
(num1,num2)=>{
}
//es5
function add(a,b){
return a+b;
}
//es6
add=(a,b)=>a+b;
6.对象初始化简写
//es5
function people(name, age) {
return {
name: name,
age: age
};
}
//es6
function people(name, age) {
return {
name,
age
};
}
7.解构
//es5
const people = {
name: 'zhangsan',
age: 20
}
const name = people.name;
const age = people.age;
console.log(name + ' ‐‐‐ ' + age);
//es6
const people = {
name: 'zhangsan',
age: 20
}
const { name, age } = people;
console.log(`${name} ‐‐‐ ${age}`);
8.Spread Operator
//数组
const color = ['red', 'yellow'];
const colorful = [...color, 'green', 'pink'];
console.log(colorful) //[red, yellow, green, pink];
//对象
const alp = { fist: 'a', second: 'b'}
const alphabets = { ...alp, third: 'c' }
console.log(alphabets) //{ "fist": "a", "second": "b", "third": "c" }