当前位置: 首页 > 后端技术 > Node.js

ES6+实用技巧,让你的代码更简洁、更短、更易读

时间:2023-04-04 00:09:17 Node.js

模板字符串letname='siri',age=18,job='前端工程师'letoldStr='Hi,'+name+',I\''+age+'andworkasa'+job+'.';letnewStr=`嗨,${name},我是${age},工作是${job}。`;Spreadoperator...运算符,主要有两个用途:复制一个新的数组或对象将多个参数赋值给一个数组变量将一个数组变量赋值给多个参数leta=[1,2,3]letb=[...a]//b是一个新数组,内容和a一样letc=[...a,4,5,6]letcar={type:'vehicle',wheels:4};letnewCar={...car}console.log(newCar);//{type:'vehicle',wheels:4}//合并对象属性,后面的属性会覆盖前面的,可以用来修改对象的某个属性值letcar2={...car,type:'vehicle2',wheels:2}//{type:"vehicle2",wheels:2}functionfoo(...args){console.log(args);}foo('汽车',54,'树');//console.logoutput['car',54,'tree']defaultparameters//给方法添加默认参数值functionfoo(a=5,b=10){console.log(a+b);}foo();//15foo(7,12);//19foo(未定义,8);//13foo(8);//18foo(空);//10因为null被强制转换为0//默认参数值也可以是表达式或函数functionfoo(a){returna*4;}//y=x+4,z=foo(x)函数bar(x=2,y=x+4,z=foo(x)){console.log([x,y,z]);}bar();//[2,6,8]栏(1,2,3);//[1,2,3]bar(10,undefined,3);//[10,14,3]//对象参数默认值,参数为空会抛出异常functionshow({title="title",width=100,height=200}){console.log(`${title}${width}${height}`);}show()//不能破坏'undefined'或'null'的属性`title`.show({})//title100200//解决方案:functionshow({title="title",width=100,height=200}={}){console.log(`${title}${width}${height}`);}show();//title100200show({width:200})//title200200解析赋值//关键变量重命名,first-->firstNameconstperson={first:'foo',last:'tom',};const{first:firstName}=person;控制台日志(名字);//foo//defaultconstsettings={speed:150}const{speed=750,width=500}=settings;console.log(speed);//150console.log(宽度);//500//可能不存在keyconst{middle:middleName='midname'}=person;安慰。日志(中间名);//'中间名'//嵌套赋值constuser={id:339,name:'Fred',age:42,education:{degree:'Masters'}};const{education:{degree}}=user;console.log(degree);//prints:Masters//如果嵌套属性不存在constuser={id:339,name:'Fred',age:42};const{教育:{学位}}=用户;//类型错误:无法匹配'undefined'或'null'。//解决方案:constuser={id:339,name:'Fred',age:42};const{教育:{学位}={}}=用户;控制台日志(度数);//prints:undefined使用数组生成数字序列constnumRange=(start,end)=>{returnArray(end-start+1).fill().map((item,index)=>start+指数);};constnumbers=numRange(0,5);//[0,1,2,3,4,5]constnumbers2=numRange(1,5);//[1,2,3,4,5]使用Set去重数组constyears=[2016,2017,2017,2018,2018,2019]//set构造函数的参数是一个arrayconstdistinctYears=[...newSet(years)]//[2016,2017,2018,2019]生成一个唯一的随机字符串,可以指定长度functiongenerateRandom(length){letradom13chars=function(){returnMath.random().toString(16).substring(2,15)}letloops=Math.ceil(length/13)returnnewArray(loops).fill(radom13chars).reduce((string,func)=>{返回字符串+func()},'').substring(0,length)}generateRandom(8)//"03836a49"