我有一些这样的代码:
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规则?
答案 0 :(得分:2)
如果条件为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();