优化嵌套的if语句

时间:2011-02-24 18:52:45

标签: javascript

他们是一种更简单的方法来模仿这种逻辑吗?

如果以下任何方法返回False,则调用的每个方法都返回True或False,然后调用this.displayError()方法。

我想不出更简单的模仿这种逻辑,任何想法?

     main: function(){
    if(this.isWRNotProcessed()){
        if(this.retriveWRMetaData()){
            if(this.retrieveWRLines()){
                this.getDistinctOrders();
                if(this.createNewPOs()){
                    this.approvePOs();
                } else{this.displayError();}
            } else{this.displayError();}
        } else{this.displayError();}    
    } else{this.displayError();}
      }

编辑:调用this.createNewPO()时添加了一个else语句 对此感到抱歉,感谢所有回复,他们都很有帮助!

Try Catch语句也可以用于此逻辑而不是IF吗?

5 个答案:

答案 0 :(得分:4)

这应该做你想要的:

main: function () {
    if (this.isWRNotProcessed() && this.retriveWRMetaData() && this.retrieveWRLines()) {
        this.getDistinctOrders();
        if (this.createNewPOs()) {
            this.approvePOs();
        }
    } else {
        this.displayError();
    }
}

答案 1 :(得分:1)

main: function(){
  if (this.isWRNotProcessed() && this.retrieveWRMetaData() && this.retrieveWRLines()){
    this.getDistinctOrders();
    if (this.createNewPOs()){
      this.approvePOs();
      return
    }
  }
  this.displayError();
}

或者我错过了什么?除非displayError特定于失败,否则这应该适用于您的目的。

答案 2 :(得分:1)

可能它会变得更加可读:

main: function()
{
   var is_valid = 
      this.isWRNotProcessed() && this.retriveWRMetaData() && this.retrieveWRLines();

   if(!is_valid)
   {
      this.displayError();
      return;
   }

   this.getDistinctOrders();

   if(this.createNewPOs())
   {
      this.approvePOs();
   }    
}

答案 3 :(得分:0)

为了简化可读性,我会再做一个方法......如果你在this.isWRNotProcessed() && this.retriveWRMetaData() && this.retrieveWRLines()true时做出某些事情,那么这是合乎逻辑的,那么应该解释一下它的含义。

 someCheck: function(){ // I don't know what exactly it does so call this way..
     return this.isWRNotProcessed() 
          && this.retriveWRMetaData()
          && this.retrieveWRLines();
 },

 main: function(){
     if(this.someCheck()){
            this.getDistinctOrders();
            if(this.createNewPOs()){
                this.approvePOs();
            }
     } else {
             this.displayError();
     }
 }

答案 4 :(得分:-2)

也许这个:

if(this.isWRNotProcessed() && this.retriveWRMetaData() && this.retrieveWRLines() &&     this.getDistinctOrders() && this.createNewPOs()) {
     this.approvePOs();
} else {
     this.displayError();
}