前言
作为一个2022年的前端工程师,是时候用一点ES6了吧?
这篇文章用于巩固你的代码习惯,提高代码水平以及ES6掌握度。
1.括号返回值
-
使用场景:假设我们需要将一个已有的变量值改变并赋予给另外一个新的值时
-
let prevValue = 3 console.log('prevValue:',prevValue)//output:prevValue: 3 let newValue = (prevValue = 7) console.log('newValue:',prevValue)//output:newValue: 7 console.log('prevValue:',prevValue)//output:prevValue: 7
将俩便赋值融合在了一块,旁人看不懂的牛逼
2.find函数
-
使用场景:根据一个值在数组中找出对应的项
-
let arr = [{name:'jack',id:'1'},{name:'john',id:2}] let result = {id:'2',name:''} const item = arr.find((item)=>{ return item.id ==result.id }) result.name = item.name
find函数为ES6 新增语法会在找到第一个匹配项时,返回并结束查找。拒绝for循环break跳出,以及try catch嵌套forEach。使用find函数,旁人看不懂的牛逼
3.解构赋值
-
使用场景:取出已有对象的值
-
const obj = { a:1, b:2, c:3, d:4, e:5, } //想用的变量名与对象中属性名一致时 let {a,b}=obj console.log(a,b)//output: 1 2 //想用的变量名与对象中属性名不同时 let {c:c1,d:d2} = obj console.log(c1,d2)//output: 3 4
ES6的解构赋值虽然好用。但是要注意解构的对象不能为
undefined
、null
。否则会报错,故要给被解构的对象一个默认值。const {a,b,c,d,e} = obj || {};
使用解构赋值,决绝傻瓜赋值,旁人看不懂的牛逼
4.includes
-
使用场景:判断目标是否为一范围内的值
-
//使用前 if( type == 1 || type == 2 || type == 3 || type == 4 || ){ //... } //改进后 const condition = [1,2,3,4]; if( condition.includes(type) ){ //... }
includes为ES6数组新增实例方法,会判断目标元素是否为数组的元素。
5.async && await
-
使用场景:处理异步函数
-
//使用前 const fn1 = () =>{ return new Promise((resolve, reject) => { setTimeout(() => { resolve(1); }, 300); }); } const fn2 = () =>{ return new Promise((resolve, reject) => { setTimeout(() => { resolve(2); }, 600); }); } const fn = () =>{ fn1().then(res1 =>{ console.log(res1);// 1 fn2().then(res2 =>{ console.log(res2) }) }) } //改进后 const fn = async () =>{ const res1 = await fn1(); const res2 = await fn2(); console.log(res1);// 1 console.log(res2);// 2 }
通过使用async && await 让链式操作变得更加直观化,解决了回调地狱的问题,旁人看不懂的牛逼
6.可选链操作符
-
使用场景:赋值为一个可能为undefined的值
-
//使用前 const name = obj && obj.name; //改进后 const name = obj?.name;
一行代码敲定,旁人看不懂的牛逼
END
本篇长期更新,有牛逼继续更新。