简体   繁体   English

执行此 If 语句的更好方法?

[英]Better way to do this If statement?

Pretty simple: I wrothe the following if/else statement:很简单:我对以下if/else语句感到不满:

   if (cr1.ins <= cr2.ins) {
     console.log("[ROUND 1] Creature 1 (#" + cr1.num + ") is attacking first.");
    cr2.hlt = cr2.hlt - (cr1.atk + cr2.ins);
    console.log("[HIT] Creature #" + cr2.num + " health reduced to " + cr2.hlt);
    if (cr2.hlt <= 0) {
      console.log("[DEATH] Creature #" + cr2.num + " Eliminated");
      remove(cr2);
    } else {
      console.log("[ROUND 2] Creature 2 (#" + cr2.num + ") is attacking second.");
      cr1.hlt = cr1.hlt - (cr2.atk + cr1.ins);
      console.log("[HIT] Creature #" + cr1.num + " health reduced to " + cr1.hlt);
      if (cr1.hlt <= 0) {
      console.log("[DEATH] Creature #" + cr1.num + " Eliminated");
      remove(cr1);
    }
    }
   } else {
    cr1.hlt = cr1.hlt - (cr2.atk + cr1.ins);
    console.log("[ROUND 1] Creature 2 (#" + cr2.num + ") is going first.");
    console.log("[HIT] Creature #" + cr1.num + " health reduced to " + cr1.hlt);
    if (cr1.hlt <= 0) {
      console.log("[DEATH] Creature #" + cr1.num + " Eliminated");
      remove(cr1);
    } else {
      console.log("[ROUND 2] Creature 1 (#" + cr1.num + ") is going second.");
      cr2.hlt = cr2.hlt - (cr1.atk + cr2.ins);
      console.log("[HIT] Creature #" + cr2.num + " health reduced to " + cr2.hlt);
      if (cr2.hlt <= 0) {
      console.log("[DEATH] Creature #" + cr2.num + " Eliminated");
      remove(cr2);
    }
    }
   }

I know there's probably a better way to do this, as the code in else{ } is basically the same as if{ } with some variable name changes, so, any suggestions for changes or refactoring?我知道可能有更好的方法来做到这一点,因为else{ }中的代码与 if{ } 基本相同, if{ }有一些变量名更改,那么,有什么更改或重构的建议吗? I'd like to improve readability and speed while accomplishing the same task as it performs currently.我想在完成与当前执行相同的任务的同时提高可读性和速度。

Indeed you can simplify this, the general approach would be事实上,你可以简化这一点,一般的方法是

if (cr1.ins > cr2.ins) {
  [cr2, cr1] = [cr1, cr2]; // just swap them!
}
attack(cr1, cr2);
if (cr2.hlt > 0) {
  attack(cr2, cr1);
}

For your logging statements with Creature 1/2 you would also need to pass through that information, so it might become something like对于使用Creature 1/2的日志记录语句,您还需要传递该信息,因此它可能会变成类似

const a = {designator: "Creature 1", creature: cr1},
      b = {designator: "Creature 2", creature: cr2};
const [first, second] = cr1.ins <= cr2.ins ? [a, b] : [b, a];
attack({attacker: first, defender: second, round: 1});
if (second.creature.hlt > 0)
  attack({attacker: second, defender: first, round: 2});

Of course, if you refactor this to use an attack function as above, it might become shorter to write out the if / else again.当然,如果您将其重构为使用上述attack function,则再次写出if / else可能会变得更短。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM