美文网首页
Improve Nested Conditionals(优化嵌套

Improve Nested Conditionals(优化嵌套

作者: 买买买买菜 | 来源:发表于2018-08-24 14:12 被阅读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]();
         }
    

    相关文章

      网友评论

          本文标题:Improve Nested Conditionals(优化嵌套

          本文链接:https://www.haomeiwen.com/subject/ogcavftx.html