ES6新特性的学习和使用
本文是基于Windows 10系统环境,进行ES6新特性的学习和使用
- Windows 10
- React
一、ES6的新语法
(1) let和const
- let 声明一个变量
- const 声明一个常量
(2) 字符串扩展
- includes(param):返回布尔值,表示是否找到了param参数字符串
- startsWith(param):返回布尔值,表示param参数字符串是否在原字符串头部
- includes(param):返回布尔值,表示param参数字符串是否在原字符串尾部
(3) 数组解构
let arr = [1, 2, 3]
const [a, b, c] = arr
console.log(a) // a= 1
console.log(b) // a= 2
console.log(c) // a= 3
(4) 对象解构
const person = {
name:'xu',
age:20,
}
const { name:newName, age:newAge } = person
console.log(newName) // newName= xu
console.log(newAge ) // newAge = 20
(5) 函数参数默认值
function add(a, b=1){
return a+b;
}
(6) 箭头函数
- 函数只有一个参数
function show(a){
console.log(a);
}
==>
const show2 = a => console.log(a);
- 函数有多个参数
function add(a,b){
console.log(a+b);
}
==>
const add2 = (a,b) => console.log(a+b);
- 函数有多个参数,且多行代码
function add(a,b){
let c = a + b
return c;
}
==>
const add2 = (a,b) =>{
let c = a+b;
return c;
}
(7) 箭头函数结合解构表达式
const person = {
name:'xu',
age:20,
}
const hello2 = ( {name} ) => console.log(name);
(8) map函数
- map函数接收一个函数,然后返回处理后的数组
let arr = [1, 2, 3]
let newArr = arr.map(item => return item+1);
// 返回 [2, 3, 4]
(9) reduce函数
- reduce函数接收一个函数和一个初始值(可选),然后返回处理后的一个数值
let arr = [1, 2, 3]
let newArr = arr.reduce((a,b)=>return a+b);
// 返回6
(10) 扩展运算符
- 扩展运算符是…,将数组或者对象转为用逗号分隔开的参数序列
console.log(...[1, 2, 3]) // 1,2,3
//数组合并
let arr = [...[1, 2, 3],...[4,5,6]]
console.log(arr) // 1,2,3,4,5,6
//与解构表达式结合
const [first, ...rest] = [1,2,3]
console.log(rest) // 2,3
(11) 异步函数Promise
- 扩展运算符是…,将数组或者对象转为用逗号分隔开的参数序列
const p = new Promise((resolve, reject)=>{
setTimeout(()=>{
let num = Math.random();
if(num<0.5){
resolve('success' + num);
} else{
reject('error' + num);
}
});
});
p.then(value=>{
console.log(value);
}).catch(error=>{
console.log(error);
})