Javascript 如何重构这个多嵌套if-else块

Javascript 如何重构这个多嵌套if-else块,javascript,if-statement,refactoring,data-driven,Javascript,If Statement,Refactoring,Data Driven,我有这种多重嵌套的if-else块。我的理解是,有一种“数据驱动”的方法可以帮助消除对它的需求并精简代码,但是,我还没有在很大程度上使用它的经验,所以有人能帮我重构代码以使用“数据驱动”的方法吗 function (arg1) { if(this.thing[arg1]){ // there is a valid property for this arg1 if(this.thing.a){ // there exists an 'a' propertie al

我有这种多重嵌套的if-else块。我的理解是,有一种“数据驱动”的方法可以帮助消除对它的需求并精简代码,但是,我还没有在很大程度上使用它的经验,所以有人能帮我重构代码以使用“数据驱动”的方法吗

function (arg1) {
  if(this.thing[arg1]){
    // there is a valid property for this arg1
    if(this.thing.a){
      // there exists an 'a' propertie also
      if(this.thing.a.arg1 == arg1){
        // the a property has a property is the same as the arg1    
        // if this 'a' has a number higher than 0, avoid doing anything
        if(this.thing.a.number > 0){
        }else{
          // 'a' number was 0 or lower, so we do something
          this.thing.a = this.thing[arg1];
          this.thing.a.arg1 = arg1;
        }
      }else{
        // the' a' is not the arg1
        // so we want to use the current arg1!
        // but only if its 'number' is lower than 1
        if(this.thing.a.number > 0){
        }else{
          // 'a' number was 0 or lower, so we do something
          this.thing.a = this.thing[arg1];
          this.thing.a.arg1 = arg1;
        }
      }
    }else{
      // there is no thing.a so we set it to arg1 
      this.thing.a = this.thing[arg1];
      this.thing.a.arg1 = arg1;
    }
  }
}

很确定你的逻辑可以归结为:

if (this.thing[arg1]) {
    //confirm or set a
    this.thing.a = this.thing.a ? this.thing.a : this.thing[arg1];

    //if a.arg1 is not thing[arg1] and a.number is less than 1
    if (this.thing.a.arg1 !== this.thing[arg1] && this.thing.a.number < 1) {
        this.thing.a = this.thing[arg1];
        this.thing.a.arg1 = arg1;   
    }
}
永远都不会是对的。不要创建空块,更改表达式,如下所示:

if (someNumber < 1) {
    //do something
}

如果您注意到重复这样的代码,请后退一步,看看如何更改逻辑流,以便只需编写一次代码。

我推荐这本书:(它改变了我的整个编码风格)谢谢!我做了一个小编辑:在第二个if嵌套中,我想要
if(this.thing.a.arg1!==this.thing[arg1]&&this.thing.a.number<1)
,然后将
.arg1
添加到
thing.a
中。在第一次运行该代码时,它没有正确地触发我的事件,在中添加它起作用了。PS:
如果(someNumber>0){/*什么都不做*/}
实际上我目前“什么都不做”,但计划在那里添加一些东西
if (someNumber < 1) {
    //do something
}
this.thing.a = this.thing[arg1];
this.thing.a.arg1 = arg1;