我有一些这样的代码:
let upgrade;
if (device.firmwareV !== latestFirmware.version) {
upgrade = "Firmware is up to date.";
} else if (!firmUpTool) {
upgrade = "Cannot upgrade the firmware through this connection.";
} else if (latestFirmware.type !== device.type) {
upgrade = "Cannot upgrade firmware of this device.";
} else {
upgrade = upgradeControl(firmUpTool);
}
但我更喜欢使用三元运算符(条件
?
value1 :
value2),因为它允许我替换 let
与 const
(在我看来它看起来更整洁,尽管我很欣赏意见不同):const upgrade =
device.firmwareV !== latestFirmware.version ?
"Firmware is up to date."
: !firmUpTool ?
"Cannot upgrade the firmware through this connection."
: latestFirmware.type !== device.type ?
"Cannot upgrade firmware of this device."
: upgradeControl(firmUpTool);
但是 ESLint 给出了 5 个错误,例如
Expected indentation of 12 spaces but found 8.
.如果我遵循建议,即使我已经给它一个缩进规则,我也必须缩进代码:indent: [2, 4, {flatTernaryExpressions: true}]
我可以通过删除每个
?
之后的换行符来消除警告。但这会使行过长,在我看来不那么可读。有没有更好的方法来布置平面嵌套三元组,或者我应该在这里使用其他一些 ESLint 规则?
最佳答案
如果条件为 true
,您可以使用检查部件并提前返回的功能。 .
优点是更好的可读性和可维护性。
失踪的else
部分被函数可能的更早退出所覆盖。
function checkUpgrade() {
if (device.firmwareV !== latestFirmware.version) {
return "Firmware is up to date.";
}
if (!firmUpTool) {
return "Cannot upgrade the firmware through this connection.";
}
if (latestFirmware.type !== device.type) {
return "Cannot upgrade firmware of this device.";
}
return upgradeControl(firmUpTool);
}
const upgrade = checkUpgrade();
关于javascript - 如何在 ESLint 中使用平面嵌套三元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53099633/