Closed. This question is opinion-based。它当前不接受答案。
                        
                    
                
            
        
            
        
                
                    
                
            
                
                    想改善这个问题吗?更新问题,以便editing this post用事实和引用来回答。
                
                    4年前关闭。
            
        

    

由于嵌套开关盒的可读性不高,我该如何优化嵌套开关盒?

switch (code) {
  case 200:
    switch (status) {
      case 'EXISTS':
        $alreadyExistsMessage.show();
        break;
      case 'UPDATED':
        $alreadyExistsMessage.show();
        break;
      case 'ERROR':
        $wrongFormatMessage.show();
        break;
    }
    break;
  case 201:
    redirectOnSuccess(data);
    break;
  default:
    $wrongFormatMessage.show();
    break;
}

最佳答案

由于相同的块,我唯一要做的是合并大小写'UPDATED''EXISTS'

switch (code) {
  case 200:
    switch (status) {
      case 'EXISTS':
      case 'UPDATED':
        $alreadyExistsMessage.show();
        break;
      case 'ERROR':
        $wrongFormatMessage.show();
        break;
    }
    break;
  case 201:
    redirectOnSuccess(data);
    break;
  default:
    $wrongFormatMessage.show();
    break;
}

07-28 11:36