【问题标题】:Refractor if statement [closed]折射if语句[关闭]
【发布时间】:2021-07-13 13:05:39
【问题描述】:

我要折射一段代码

if (res1 && res1.e > maxEnergy) {
    maxRes = res1;
    maxEnergy = res1.e;
}
if (res2 && res2.e > maxEnergy) {
    maxRes = res2;
    maxEnergy = res2.e;
}
if (res3 && res3.e > maxEnergy) {
    maxRes = res3;
    maxEnergy = res3.e;
}

有没有最好的方法在较短的段中完成这段代码? 使用 Object 字面量或 switch 语句?

【问题讨论】:

  • res1 && res1.e > maxEnergy => res1?.e > maxEnergy
  • 实际上,我希望将所有三个 if 合并为一个简短的版本,而不仅仅是它们的条件
  • 可能是Math.max(...[res1?.e || 0, res2?.e || 0, res3?.e || 0, maxEnergy]) 之类的
  • 就这样吧。至少坚持的人以后不必绞尽脑汁来理解应该会发生什么。我更喜欢每天保持干净/注释/可理解的代码而不是缩小的简写单行。
  • 如果可能的话,我更喜欢循环和数组:[res1, res2, res3].forEach(res => {if (res?.e > maxEnergy) { maxRes = res; maxEnergy = res.e; });

标签: javascript switch-statement object-literal


【解决方案1】:

更短且可读性更强(恕我直言,更具可读性):

[res1, res2, res3].forEach(res => {
  if (res?.e > maxEnergy) {
    maxRes = res;
    maxEnergy = res.e;
  }
});

【讨论】:

  • 为什么在 for-of 循​​环中使用 forEach?
  • @Sadiinso 恕我直言,首先查看我迭代的项目列表更具可读性。在 for-of 循​​环中,项目列表位于第一行的末尾附近。不那么可读。在行首格式化长数组比在循环头中更容易。
  • 迭代项确实排在第一位,但这会以 lambda 表达式的形式引入一些噪音。但正如你所说,这更多的是个人喜好。
  • @Sadiinso 这个“lambda 表达式形式的噪声” 是 JavaScript 非常典型的。我什至认为forEach 循环比for-of 循环更具JavaScript 风格。它更适合filter 和map 的环境。
  • @Sadiinso 使用for-of 循环代替forEach 是一种观点,但使用for-of 代替filter、map、sort、flatMap、.. . 只是糟糕的代码风格。这不是函数式与命令式编程风格的问题。
【解决方案2】:

只是对这个问题的另一种看法。当我看到某些操作被重复(if 语句)时,我喜欢将该代码移动到一个函数中,以便稍后在其他上下文中使用它。

let currentMax= {
    e: 0
}

const res1 = {
    e: 90
};
const res2 = {
    e: 170
};
const res3 = {
    e: 10
};

function findMaxEnergy(res, currentMaxRes) {
  if (res && res.e > currentMaxRes.e) {
    return res;
  }
  return currentMaxRes;
}

// now you can use it one by one
// currentMax = findMaxEnergy(res1, currentMax);
// currentMax = findMaxEnergy(res2, currentMax);
// currentMax = findMaxEnergy(res3, currentMax);

// or with an array and a loop
[res1, res2, res3].forEach(res => {
  currentMax = findMaxEnergy(res, currentMax);
});

console.log(currentMax);

【讨论】:

    猜你喜欢
    • 2017-09-05
    • 2016-10-15
    • 2017-05-24
    • 2014-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多