今天我将分享一些编写干净JavaScript代码的技巧!1.更好的命名在JavaScript中,好的命名的关键不是最短的变量名,而是最具有描述性的变量名。(1)减少magicnumber,将代码中的一些数字定义为常量,使其更有意义,方便后期维护。?for(i=0;i<8765;i++){}?constHOURS_IN_A_YEAR=8765for(i=0;i{constuser=awaitUser.findByPk(userId)if(user.isSubscribed){constNotification=awaitNotifications.create({date:newDate(),user_id:userId,消息,emailNotify:true});Notification.save();}else{constNotification=awaitNotifications.create({date:newDate(),user_id:userId,message,emailNotify:true});Notification.save();}}}?异步函数notifyUsers(userIds,message){userIds.foreach(userId=>{constuser=awaitUser.findByPk(userId)notifyUsers(userId,message,user.isSubscribed)}}asyncfunctioncreateNotification(userId,message,isSubscribed){constNotification=awaitNotifications.create({date:newDate(),user_id:userId,消息,emailNotify:isSubscribed});Notification.save();}(2)使用递归在某些情况下,使用递归的代码会比迭代更简洁?conststepsToHundred=(number)=>{letsteps=0while(number<100){number*=2steps++}returnsteps}?conststepsToHundred=(number,steps)=>number<100?stepsToHundred(number*2,steps+1):steps(3)ES6中加入的字符串拼接模板字符串函数让我们在拼接字符串的时候可以让代码更短更简洁。?constwelcomeMessage="你好"+user1+",我是"+user2;?constwelcomeMessage=`你好${user1},我是${user2}`3、减少多层嵌套(1)条件语句不要在if-else里面嵌套return语句。?constgetUSTime=(time)=>{if(time<=12){返回时间+"AM"}else{返回时间+"PM"}}?constgetUSTime=(time)=>{if(time<=12)returntime+"AM"returntime+"PM"}也可以用三元表达式写成:constgetUSTime=(time)=>{returntime+(time<=12?"AM":"PM")}(2)async/await当使用chainedPromises时,代码的可读性会变差。Async/await可用于优化异步嵌套代码。?constsharePost=()=>{getPost().then(post=>{sendTweet(post.url,`分享帖子:${post.title}`).then(()=>{console.log("分享成功");});});}?constsharePost=async()=>{constpost=awaitgetPost();awaitsendTweet(post.url,`Shareapost:${post.title}`)console.log("Sharingsuccess");}4.干净的函数(1)处理大量参数的函数。当函数有很多参数时,按顺序传递参数非常麻烦。可以用一个对象把所有的参数都包裹起来,这样传参的时候可以乱序传参,避免传参的时候出错。?functionaddUser(firstName,lastName,age,city,state,zipCode){//...}?functionaddUser({firstName,lastName,age,city,state,zipCode}){//...}(2)TheSingleResponsibilityPrinciple使用单一职责原则,你可以轻松命名函数,每个函数只做一件事。看名字就可以确切的知道这个函数是干什么的,不会冗长。?异步函数signupUser(email){constuser=awaitUser.create({email});等待user.save();constnotifcation=awaitNotification.create({email});等待通知。保存();constdate=newDate()Log.add(date,"Signup",email)}?constlogSignup(email)=>Log.add(newDate(),"Signup",email)异步函数signupUser(email){createUser(email)notifyUser(email)logSignup(email)}asyncfunctioncreateUser(email){constuser=awaitUser.create({email});awaituser.save();}asyncfunctionnotifyUser(email){constnotifcation=awaitNotification.create({email});awaitnotifcation.save();}(3)回调中首选箭头函数在JavaScript中,map、filter等方法需要一个匿名函数作为参数。在这些情况下,使用箭头函数是最方便和优雅的方式?[1,2,3].forEach(function(x){consty=x**2;returnx+y;});?[1,2,3]。forEach((x)=>{consty=x**2;returnx+y;});