【问题标题】:simplification of 2 if statements into a loop将 2 个 if 语句简化为循环
【发布时间】:2015-12-02 15:29:33
【问题描述】:

我想简化一段代码 sn-p,其中我有一个主循环,我在其中放置了 2 个 if 语句。第一个 if 语句是关于一个测试“if (test1 or test2)”,第二个是一个测试“if (test1 and test2)”。

目前,为了区分它们,我必须在更高级别(但仍在主循环中)放置另一个“if”(在diagExpression boolean 上测试,见下文);这是代码:

// Main loop 
  while (Hit.arrayCurrent[Hit.coordCurrent[0]+k][Hit.coordCurrent[1]+l] == Hit.currentPlayer[1]) 
  {   
   if (diagExpression)
     {   
      if ((a > b) || (b > c))
        return;
      else if (d)
       {   
        //do stuff1
       }   
     }   
  else
    {   
     if ((a > b) && (b > c))
        return;
     else if (d)
       {   
        //do stuff1
       }   
     }   
  }

我不知道如何简化此代码 sn-p 并避免使用 stuff1 2 次。

如果有人能找到解决方案。

更新:

diagExpression 在主循环之前计算:

// Boolean for 2 versions
  var diagExpression = false;

  if (Hit.direction == 'rightbottom')
    { 
      diagExpression = true;
      shift_x = 1;
      shift_y = 1;
      factor_x = 1;
      factor_y = 1;
      limit_x = 7;
      limit_y = 7;
    }
 else if (Hit.direction == 'left')
    {
      shift_x = -1;
      shift_y = 0;
      factor_x = -1;
      factor_y = 1;
      limit_x = 0;
      limit_y = -1;
    }

...

// Main loop 
  while (Hit.arrayCurrent[Hit.coordCurrent[0]+k][Hit.coordCurrent[1]+l] == Hit.currentPlayer[1])

我在我的代码中使用了不同的方向值,如果我有对角线方向,这个布尔值为真,垂直/水平方向为假。

【问题讨论】:

  • 请您的 diagExpression ..请确保代码读取良好..还要标记使用的语言
  • diagExpression 是一个布尔值,在主循环之前计算。这是Javascript语言
  • 把两个return放在上面。在他们两个之后,以便只有没有返回的代码执行它,写if (d) //do stuff1,就一次。

标签: javascript algorithm if-statement simplify


【解决方案1】:

首先你可以简化你的代码,这样你只需要编写一次stuff1

while (…) {   
  if (diagExpression) {  
    if ((a > b) || (b > c))
      return;
  } else {
    if ((a > b) && (b > c))
      return;
  }
  if (d) {
    // do stuff1
  }
}

甚至

while (…) {   
  if (diagExpression ? (a > b) || (b > c) : (a > b) && (b > c)) {
    return;
  } else if (d) {
    // do stuff1
  }
}

然后你可以得到更高级的东西,比如

while (…) {   
  if ((a > b) + (b > c) >= 2 - diagExpression) {
    return;
  } else if (d) {
    // do stuff1
  }
}

虽然这变得相当不可读,甚至可能更慢。

【讨论】:

    【解决方案2】:

    你可以这样使用:

    if (diagExpression) {
         if ((a > b) || (b > c))
            return;
         if ((a > b) && (b > c))
            return;
    }
    if (d){   
         //do stuff1
    } 
    

    这也是我认为@Daniel Daranas 的意思。

    【讨论】:

    • 不完全是。你需要一个 if (diagExpression) 的 else 并把 if ((a > b) && (b > c)) 放在那里,就像 other answer 一样。否则你正在改变行为。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-12
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    相关资源
    最近更新 更多