如何简化以下if语句和三元运算符?
以下代码位于循环遍历表单字段的循环中。如果isV1User
是true
,则该字段被禁用。如果用户有customSetting
则不要禁用该字段。如果用户没有它,请禁用它。如何简化以下if语句和三元运算符?
if (field.name === 'themeColor') {
if (this.isV1User) {
field.disabled = false
} else {
field.disabled = this.user.customSetting
? !this.user.customSetting.themePicker
: false
}
}
如何简化或至少删除此代码的嵌套?
每移动if
条件三元:
if (field.name === 'themeColor') {
field.disabled = !this.isV1User && this.user.customSetting && !this.user.customSetting.themePicker;
}
if (field.name === 'themeColor') {
field.disabled = this.user.customSetting && !this.isV1User ?
!this.user.customSetting.themePicker : false;
}
这是不是一个真正的堆栈溢出的问题,将适合在代码审查好我猜。
只有一组情况需要true
,看起来,所以也许这样?
if (field.name === 'themeColor') {
field.disabled = (
!this.isV1User &&
this.user.customSetting && !this.user.customSetting.themePicker);
}
第一if
还是需要的,因为其他领域应保持不变(我假设)。
试试这个
if (field.name === 'themeColor') {
field.disabled = this.isV1User ? true : this.user.customSetting ? !this.user.customSetting.themePicker : false;
}
你确定你的代码工作?三元操作符是从右到左的,也是* pro-tip *没有任何'()'的多个三元操作符是非常**混淆且难以阅读的。 – Justinas
你可以这样做
"themeColor"===field.name && (field.disabled=this.isV1User?!1:
this.user.customSetting?!this.user.customSetting.themePicker:!1);
如果字段名称不是'themeColor',那么您仍然会更改'disabled'属性字段。 – Justinas
您已经构建你的代码的方式,可以最小化到下面的等效代码。请注意,如果this.user.customSetting.themePicker
是保证始终是真实的,当this.user.customSetting
是真实的,你可以在一个单一的if语句,其中条件是field.name == 'themeColor'
设置field.disabled = true
:
if (field.name == 'themeColor' && this.user.customSetting) {
field.disabled = !this.user.customSetting.themePicker;
} else if (field.name == 'themeColor') {
field.disabled = false;
}
甚至以下switch语句,这取决于你如何想你的代码结构化。他们都是一样的。
switch (field.name) {
case 'themeColor':
if (this.user.customSetting) {
field.disabled = !this.user.customSetting.themePicker;
}
break;
default:
field.disabled = false;
}
这些答案大多打破了三元语句可读性的基本规则。如果你的目标是简单的可读性,将其分解成简单的if/else if
声明就可以了。如果您试图尽可能减少代码,并且不在乎它是不可维护还是难以阅读,则应该将其简化为递归三元语句。就我个人而言,我发现冗长的三元陈述并不能提供显着的节省空间,阻碍可读性,并且在它们不是非常简单的情况下应避免(即:var x = statement? 1 : 0;
)
为什么? (他想简单地问,但是*需要更多的字符) – CBroe
_“如果isV1User为true,那么该字段被禁用。如果用户有customSetting,那么不要禁用该字段。如果用户没有,禁用它。“_ - 所以,简单地说,禁用它,如果用户是V1用户或用户没有自定义设置...? – CBroe
你应该发布你的问题到https://codereview.stackexchange.com/ –