ES6中有条件地分配常量的最佳方法是什么?

Mid*_*rse 12 ecmascript-6

我想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)

但无论如何,三元运算符看起来更好,特别是如果它分成几行.

  • 老实说,如果有多个条件,我会避免使用三元。为此,我实际上并不介意内联函数。它更加清晰,并允许您使用“const”而不是“let”。 (2认同)
  • 事实上 eslint 默认情况下会标记嵌套三元组 (2认同)