一、es6详解
1.1 let/const
-
禁止重复声明
-
const 控制修改
-
支持块级作用域
只在 { } 作用域下起作用
1.2 解构赋值
let {a,b,c} = json ;
let [a,bc,c] = array;
1.3 函数
1.3.1 箭头函数
//普通函数
function (param){
};
//箭头函数
(param)=>{
};
//有且仅有一个参数,()也可以省略;有且仅有一条语句,{} 也可以省略
修复this,箭头函数的 this 由上下文决定,function 的 this 会因为赋值发生变更
1.3.2 参数展开
- 剩余参数
let show = (a,b,c,...arr)=>{
};
show(1,2,3,4,5,6,7,8)
- 展开数组
let arr = [1, 2, 3]
let sum = (a, b, c) => {
return a + b + c;
}
console.log(sum(...arr))
1.4 系统对象
1.4.1 Array
- map(映射)1对1
let arr = [1, 2, 3]
let res = arr.map(item => item >= 2)
console.log(res)
//[ false, true, true ]
- reduce(减少)多对1
let arr = [1,2,3]
const reducer = (accumulator,currentValue) => accumulator + currentValue;
let res = arr.reduce(reducer)
console.log(res);
//6
-
forEach(遍历)
-
filter(过滤)
1.4.2 String
- startsWith
const str1 = 'Saturday night plans';
console.log(str1.startsWith('Sat'));
// expected output: true
- endsWith
1.4.3 JSON
- JSON对象
//json对象 转 json字符串
let json = {a: 12, b: 14, c: "16"};
let jsonStr = JSON.stringify(json);
console.log(jsonStr);
//json字符串 转 json对象
JSON.parse('{"a":12,"b":14,"c":"16"}')
1.5 异步处理
1.5.1 Promise
const promise = new Promise(function(resolve, reject) {
// ... some code
if (/* 异步操作成功 */){
resolve(value);
} else {
reject(error);
}
});
promise.then(function(value) {
// success
}, function(error) {
// failure
});
/*---------------Promise.all------------------*/
const p = Promise.all([p1, p2, p3]); //p1、p2、p3都是 Promise 实例
//1. 只有p1、p2、p3的状态都变成fulfilled,p的状态才会变成fulfilled,此时p1、p2、p3的返回值组成一个数组,传递给p的回调函数。
//2.只要p1、p2、p3之中有一个被rejected,p的状态就变成rejected,此时第一个被reject的实例的返回值,会传递给p的回调函数。
1.5.2 async/awiat
async function getSomeResult() {
const stepOneResult = await getStepOne(); //getStepOne异步操作,返回 Promise 对象
const stepTwoResult = await getStepTwo(stepOneResult);
return stepTwoResult;
}
//async 返回的是 Promise 对象
getSomeResult().then(function (result) {
console.log(result);
});
1.6 Babel(es6 兼容性问题)
- 安装 node
- 安装所需模块
npm i @babel/core
npm i @babel/cli
npm i @babel/preset-env
package.json添加脚本
{
"scripts":{
"build":"babel src -d dest"
}
}
.babelrc声明 preset
{
"preset":["@babel/preset-env"]
}
- 执行脚本
npm run build