我想const validation
根据条件分配给我一个值.
如果this.showRequired() == true
那应该是'required'
否则this.showError() == true
它应该是'error'
.
我当然知道我可以将它提取到函数或级联三元运算符,但第一个看起来代码膨胀,后者丑陋.
有没有更好的方法呢?if-else表达式可能吗?
Leo*_*tny 24
级联三元运算符对我来说很好看:
const validation = this.showRequired() ? 'required' : this.showError() ? 'error' : null
Run Code Online (Sandbox Code Playgroud)
如果您认为此行太长,您可以将其拆分:
const validation = this.showRequired() ? 'required'
: this.showError() ? 'error'
: null
Run Code Online (Sandbox Code Playgroud)
或者您可以使用&&
而||
不是:
const validation = (this.showRequired() && 'required') ||
(this.showError() && 'error')
Run Code Online (Sandbox Code Playgroud)
至于将此代码移植到单独的函数中,您始终可以使用内联函数而不是创建另一个类方法:
const validation = (() => {
if (this.showRequired()) {
return 'required'
} else if (this.showError()) {
return 'error'
}
})()
Run Code Online (Sandbox Code Playgroud)
但无论如何,三元运算符看起来更好,特别是如果它分成几行.
归档时间: |
|
查看次数: |
8537 次 |
最近记录: |