Improve Nested Conditionals(优化嵌套的条件语句) 面对大量的if-else语句

//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]();
     }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容