首页/前端性能优化/前端优化:js优化if else

前端优化:js优化if else

发布-xiaoming | 浏览量-

在实际工作中面对大量的if-else语句,如何提高效率,前端开发优雅的写代码,总结4种供参考

 

 //method1

     if (color) {
         if (color === 'black') {
             printBlackBackground();
         } else if (color === 'red') {
             printRedBackground();
         } else if (color === 'blue') {
             printBlueBackground();
         } else if (color === 'green') {
             printGreenBackground();
         } else {
             printYellowBackground();
         }
     }
     
 //method2
     switch(color) {
         case 'black':
             printBlackBackground();
             break;
         case 'red':
             printRedBackground();
             break;
         case 'blue':
             printBlueBackground();
             break;
         case 'green':
             printGreenBackground();
             break;
         default:
             printYellowBackground();
     }
     
 //method3
     switch(true) {
         case (typeof color === 'string' && color === 'black'):
             printBlackBackground();
             break;
         case (typeof color === 'string' && color === 'red'):
             printRedBackground();
             break;
         case (typeof color === 'string' && color === 'blue'):
             printBlueBackground();
             break;
         case (typeof color === 'string' && color === 'green'):
             printGreenBackground();
             break;
         case (typeof color === 'string' && color === 'yellow'):
             printYellowBackground();
             break;
     }
     
 //method4
     var colorObj = {
         'black': printBlackBackground,
         'red': printRedBackground,
         'blue': printBlueBackground,
         'green': printGreenBackground,
         'yellow': printYellowBackground
     };
     if (color in colorObj) {
       colorObj[color]();
     }

原文地址:http://www.35ui.cn/post/20171021687.html

标签前端优化jsif else

上一条: node.js 开启服务代码 |nodejs搭建本地http服务器代码
下一条: vue与后端数据交互(ajax):vue-resource

或许你还对下面的文章感兴趣