简体   繁体   English

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

[英]Javascript one line If...else...else if statement

I know you can set variables with one line if\/else statements by doing var variable = (condition) ? (true block) : (else block)<\/code>我知道你可以通过var variable = (condition) ? (true block) : (else block)<\/code> var variable = (condition) ? (true block) : (else block)<\/code> , but I was wondering if there was a way to put an else if statement in there. var variable = (condition) ? (true block) : (else block)<\/code> ,但我想知道是否有办法在其中放置 else if 语句。 Any suggestions would be appreciated, thanks everyone!任何建议将不胜感激,谢谢大家!

"

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

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

tl;dr tl;博士

Yes, you can... If a then a, else if b then if c then c(b), else b, else null是的,你可以......如果a然后a,否则如果b那么如果c那么c(b),否则b,否则为空

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

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

longer version更长的版本

Ternary operator ?: used as inline if-else is right associative .三元运算符?:用作内联 if-else is right associative In short this means that the rightmost ?总之这意味着最右边的? gets fed first and it takes exactly one closest operand on the left and two , with a : , on the right.首先被喂食,它在左边正好有一个最接近的操作数,在右边有两个:

Practically speaking, consider the following statement (same as above) :实际上,请考虑以下语句(同上)

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

The rightmost ?最右边? gets fed first, so find it and its surrounding three arguments and consecutively expand to the left to another ?首先被喂食,所以找到它和它周围的三个参数并连续向左扩展到另一个? . .

   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)

This is how computers read it:计算机是这样读的:

  1. Term a is read.期限a读。
    Node: a节点: a
  2. Nonterminal ?非终结符? is read.已读。
    Node: a ?节点: a ?
  3. Term a is read.期限a读。
    Node: a ? a节点: a ? a a ? a
  4. Nonterminal : is read.非终端:被读取。
    Node: a ? a :节点: a ? a : a ? a :
  5. Term b is read.读取b
    Node: a ? a : b节点: a ? a : b a ? a : b
  6. Nonterminal ?非终结符? is read, triggering the right-associativity rule.被读取,触发右结合规则。 Associativity decides:关联性决定:
    node: a ? a : (b ?节点: a ? a : (b ? a ? a : (b ?
  7. Term c is read.读取c
    Node: a ? a : (b ? c节点: a ? a : (b ? c a ? a : (b ? c
  8. Nonterminal ?非终结符? is read, re-applying the right-associativity rule.读取,重新应用右结合规则。
    Node: a ? a : (b ? (c ?节点: a ? a : (b ? (c ? a ? a : (b ? (c ?
  9. Term c(b) is read.读取c(b)
    Node: a ? a : (b ? (c ? c(b)节点: a ? a : (b ? (c ? c(b) a ? a : (b ? (c ? c(b)
  10. Nonterminal : is read.非终端:被读取。
    Node: a ? a : (b ? (c ? c(b) :节点: a ? a : (b ? (c ? c(b) : a ? a : (b ? (c ? c(b) :
  11. Term b is read.读取b
    Node: a ? a : (b ? (c ? c(b) : b节点: a ? a : (b ? (c ? c(b) : b 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) :节点: a ? a : (b ? (c ? c(b) : b) : a ? a : (b ? (c ? c(b) : b) :
  13. Term null is read.读取null
    Node: a ? a : (b ? (c ? c(b) : b) : null节点: a ? a : (b ? (c ? c(b) : b) : null 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) #Result 是: a ? a : (b ? (c ? c(b) : b) : null) a ? a : (b ? (c ? c(b) : b) : null)

Better readability更好的可读性

The ugly oneliner from above could (and should) be rewritten for readability as:上面丑陋的 oneliner 可以(并且应该)为了可读性而重写为:
(Note that the indentation does not implicitly define correct closures as brackets () do.) (请注意,缩进并没有像括号 () 那样隐式定义正确的闭包。)

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

for example例如

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

More reading更多阅读

Mozilla: JavaScript Conditional Operator Mozilla:JavaScript 条件运算符
Wiki: Operator Associativity Wiki:运算符结合性


Bonus: Logical operators奖励:逻辑运算符

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

Using logical operators as in this example is ugly and wrong, but this is where they shine...在这个例子中使用逻辑运算符是丑陋和错误的,但这就是它们的亮点......

"Null coalescence" “零聚结”

This approach comes with subtle limitations as explained in the link below.这种方法有一些细微的限制,如下面的链接中所述。 For proper solution, see Nullish coalescing in Bonus2.有关正确的解决方案,请参阅 Bonus2 中的 Nullish 合并。

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

Short-circuit evaluation短路评估

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

Logical operators 逻辑运算符
Null coalescence空聚结
Short-circuit evaluation 短路评估


Bonus2: new in JS Bonus2:JS 中的新功能

Proper "Nullish coalescing"正确的“空合并”

developer.mozilla.org~Nullish_coalescing_operator 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
  ..
}

Optional chaining可选链

Stage 4 finished proposal https://github.com/tc39/proposal-optional-chaining https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining第 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 x = (day == "yes") ? "Good Day!" : (day == "no") ? "Good Night!" : "";

This is use mostly for assigning variable, and it uses binomial conditioning eg.这主要用于分配变量,它使用二项式条件,例如。

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

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

There is no ElseIf, for the sake of development don't use chaining, you can use switch which is much faster if you have multiple conditioning in .js没有 ElseIf,为了开发,不要使用链接,如果你在 .js 中有多个条件,你可以使用switch ,这会快得多

I know this is an old thread, but thought I'd put my two cents in. Ternary operators are able to be nested in the following fashion:我知道这是一个旧线程,但我想我会投入我的两分钱。三元运算符能够以以下方式嵌套:

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

Example:例子:

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

You can chain as much conditions as you want.您可以根据需要链接尽可能多的条件。 If you do:如果你这样做:

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

You will get x="2true"你会得到x="2true"

So it could be expressed as:所以可以表示为:

var variable = (condition) ? (true block) : ((condition)?(true block):(false block))
  a === "a" ? do something
: a === "b" ? do something
: do something

if-else:如果别的:

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

if-else if-else: if-else if-else:

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

if:如果:

a = b && (true block)

if-else-if(nested): if-else-if(嵌套):

a = b ? (true block) : b = c && (true block)
  • note think so much, just implement and see the results, where a, b and c is variable注意想了这么多,直接执行看看结果,其中a,b,c是可变的

if i use code like this如果我使用这样的代码

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

it will get它会得到

Extract this nested ternary operation into an independent statement.将这个嵌套的三元运算提取成一个独立的语句。

from so i recommend to use this从所以我建议使用这个

const alpha = a || b || c

it works for me这个对我有用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM