Javascript 一行 If...else...else if 语句

Javascript one line If...else...else if statement

我知道您可以通过 var variable = (condition) ? (true block) : (else block) 用一行 if/else 语句设置变量,但我想知道是否有办法在其中放置 else if 语句。任何建议将不胜感激,谢谢大家!

当然,您可以使用嵌套的三元运算符,但它们很难阅读。

var variable = (condition) ? (true block) : ((condition2) ? (true block2) : (else block2))

您可以根据需要链接任意多的条件。如果你这样做:

var x = (false)?("1true"):((true)?"2true":"2false");

您将获得x="2true"

所以可以表示为:

var variable = (condition) ? (true block) : ((condition)?(true block):(false block))

这主要用于分配变量,它使用二项式条件,例如。

var time = Date().getHours(); // or something

var clockTime = time > 12 ? 'PM' : 'AM' ;

没有 ElseIf,为了开发不要使用链接,你可以使用 switch 如果你在 .js 中有多个条件,速度会快得多

tl;博士

是的,你可以... If a then a, else if b then if c then c(b), else b, else null

a ? a : (b ? (c ? c(b) : b) : null)

a
  ? a
  : b
      ? c
        ? c(b)
        : b
      : null

更长的版本

用作内联 if-else 的三元运算符 ?:右结合。简而言之,这意味着最右边的 ? 首先被喂食,它恰好需要 one 最接近左侧的操作数和 two,其中:,右边

实际上,考虑以下语句(同上):

a ? a : b ? c ? c(b) : b : null

最右边的?先被喂食,所以找到它和它周围的三个参数并向左连续扩展到另一个?

   a ? a : b ? c ? c(b) : b : null
                 ^                  <---- RTL
1.            |1-?-2----:-3|
             ^ <-
2.        |1-?|--2---------|:-3---|
     ^ <-
3.|1-?-2-:|--3--------------------|

result: a ? a : (b ? (c ? c(b) : b) : null)

计算机是这样读取它的:

  1. Term a is read.
    Node: a
  2. Nonterminal ? is read.
    Node: a ?
  3. Term a is read.
    Node: a ? a
  4. Nonterminal : is read.
    Node: a ? a :
  5. Term b is read.
    Node: a ? a : b
  6. Nonterminal ? is read, triggering the right-associativity rule. Associativity decides:
    node: a ? a : (b ?
  7. Term c is read.
    Node: a ? a : (b ? c
  8. Nonterminal ? is read, re-applying the right-associativity rule.
    Node: a ? a : (b ? (c ?
  9. Term c(b) is read.
    Node: a ? a : (b ? (c ? c(b)
  10. Nonterminal : is read.
    Node: a ? a : (b ? (c ? c(b) :
  11. Term b is read.
    Node: a ? a : (b ? (c ? c(b) : b
  12. Nonterminal : is read. The ternary operator ?: from previous scope is satisfied and the scope is closed.
    Node: a ? a : (b ? (c ? c(b) : b) :
  13. Term null is read.
    Node: a ? a : (b ? (c ? c(b) : b) : null
  14. No tokens to read. Close remaining open parenthesis.
    #Result is: a ? a : (b ? (c ? c(b) : b) : null)

更好的可读性

为了便于阅读,可以 (并且应该) 将上面的丑陋的单行代码重写为:
(请注意,缩进确实 而不是 隐含地定义了正确的闭包,就像方括号 () 所做的那样。)

a
  ? a
  : b
      ? c
        ? c(b)
        : b
      : null

例如

return a + some_lengthy_variable_name > another_variable
        ? "yep"
        : "nop"

多读书

Mozilla: JavaScript Conditional Operator
Wiki: Operator Associativity


奖励:逻辑运算符

var a = 0 // 1
var b = 20
var c = null // x=> {console.log('b is', x); return true} // return true here!

a
  && a
  || b
      && c
        && c(b) // if this returns false, || b is processed
        || b
      || null

在此示例中使用逻辑运算符是丑陋且错误的,但这正是它们的亮点...

“空合并”

这种方法有一些微妙的限制,如下面的 link 所述。有关正确的解决方案,请参阅 Bonus2 中的 Nullish 合并。

function f(mayBeNullOrFalsy) {
  var cantBeNull = mayBeNullOrFalsy || 42                    // "default" value
  var alsoCantBe = mayBeNullOrFalsy ? mayBeNullOrFalsy : 42  // ugly...
  ..
}

Short-circuit评价

false && (anything) // is short-circuit evaluated to false.
true || (anything)  // is short-circuit evaluated to true.

Logical operators
Null coalescence
Short-circuit evaluation


奖励 2:JS 中的新功能

正确的“无效合并”

developer.mozilla.org~Nullish_coalescing_operator

function f(mayBeNullOrUndefined, another) {
  var cantBeNullOrUndefined = mayBeNullOrUndefined ?? 42
  another ??= 37 // nullish coalescing self-assignment
  another = another ?? 37 // same effect
  ..
}

可选链接

第 4 阶段完成提案 https://github.com/tc39/proposal-optional-chaining https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

// before
var street = user.address && user.address.street
// after
var street = user.address?.street

// combined with Nullish coalescing
// before
var street = user.address
  ? user.address.street
  : "N/A"

// after
var street = user.address?.street ?? "N/A"

// arrays
obj.someArray?.[index]

// functions
obj.someMethod?.(args)

我知道这是一个旧话题,但我想我应该投入两分钱。三元运算符可以按以下方式嵌套:

var variable = conditionA ? valueA : (conditionB ? valueB: (conditionC ? valueC : valueD));

示例:

var answer = value === 'foo' ? 1 :
    (value === 'bar' ? 2 : 
        (value === 'foobar' ? 3 : 0));

简单来说:

var x = (day == "yes") ? "Good Day!" : (day == "no") ? "Good Night!" : "";
  a === "a" ? do something
: a === "b" ? do something
: do something

如果-其他:

a = b ? (true block) : (false block)

if-else 如果-else:

a = b ? (true block) : b = c ? (true block) : (false block)

如果:

a = b && (true block)

if-else-if(嵌套):

a = b ? (true block) : b = c && (true block)
  • note 想了这么多,直接执行看看结果,其中a,b,c是可变的

如果我使用这样的代码

const alpha = a ? a : b ? b : c

会得到

Extract this nested ternary operation into an independent statement.

所以我推荐使用这个

const alpha = a || b || c

对我有用