【问题标题】:JS Nested Ternary with Multiple conditions具有多个条件的 JS 嵌套三元
【发布时间】:2020-07-22 21:40:50
【问题描述】:

基本上我有以下问题:

if condition A & B are true ->. do thing A
if only condition A is true -> do thing B 
else -> do thing C

我试过这个:

const myThing = conditionA ? conditionB ? thingA :
conditionA ? thingB : thingC;

它不喜欢语法,但我不确定它有什么问题。

【问题讨论】:

  • condition A & B are true 那是conditionA && conditionB ? thingA 不是conditionA ? conditionB ? thingA

标签: javascript reactjs conditional-operator


【解决方案1】:
const myThing =
  conditionA && conditionB ? thingA : conditionA ? thingB : thingC;

【讨论】:

  • 多条件的JS嵌套三元如何?
【解决方案2】:

您已经用if/else 写出了逻辑,那么为什么不在 IIFE 中这样做呢?它会比使用条件运算符更具可读性:

const myThing = (() => {
  if (conditionA && conditionB) {
    return thingA;
  } else if (conditionA) {
    return thingB;
  } else {
  return thingC;
  }
})();

你也可以把它放到一个独立的函数中:

const getThing = (conditionA, conditionB, conditionC) => {
  if (conditionA && conditionB) {
    return thingA;
  } else if (conditionA) {
    return thingB;
  } else {
  return thingC;
  }
};
const myThing = getThing(conditionA, conditionB, conditionC);

与其重复conditionA 测试,不如先测试它的否定,让它更简单一点:

const getThing = (conditionA, conditionB, conditionC) => {
  if (!conditionA) {
    return thingC;
  } else if (conditionB) {
    return thingB;
  } else {
    return thingA;
  }
};

【讨论】:

    【解决方案3】:

    尝试使用:

    const myThing = conditionA?(conditionB?thingA:thingB):thingC;
    

    希望对你有帮助。

    您的代码的问题是您的三元运算需要 2 个表达式,一个如果条件为真,另一个如果条件为假但在您的代码中没有提到给定的假条件:

    conditionA ? thingB 
    

    部分代码。

    【讨论】:

      【解决方案4】:

      你实际上想写的似乎是

      const myThing = conditionA ? conditionB ? thingA : thingB : thingC;
      

      但我确实建议您写这篇文章,因为您已经体验过和写要困难得多。我添加这个只是为了解释条件运算符是如何工作的,并且希望证明你不应该将它们用于任何远程复杂的事情。我发现一般条件的应用非常有限,如果从未使用过,我不会错过它。 Use if/else instead.

      为清楚起见,该表达式的解析如下:

      const myThing = conditionA ? (conditionB ? thingA : thingB) : thingC;
      
      • 如果conditionAtrue - 评估第二个条件运算符
        • 如果conditionBtrue - 返回thingA
        • 如果conditionBfalse - 返回thingB
      • 如果conditionAfalse - 返回thingC

      这在布尔逻辑组合中发挥作用

      if (A) {
        if (B) {}
      }
      

      相当于将两个条件通过AND组合

      if (A && B) ()
      

      但是,嵌套表达式使得理解正在发生的事情变得更加困难,因为您需要在心理上映射整个表达式才能理解它。比较这两个

      const x = A ? B ? C ? "one" : "two" : "three" : "four";
      

      if (A && B && C) return "one";
      if (A && B) return "two";
      if (A) return "three";
      
      return "four"
      

      对于后者,您一次只需要理解一个表达式即可找出返回的内容,对于前者,您需要所有表达式。

      【讨论】:

        猜你喜欢
        • 2017-12-14
        • 1970-01-01
        • 1970-01-01
        • 2016-11-02
        • 1970-01-01
        • 2015-10-28
        • 2012-08-24
        • 2020-11-09
        • 2020-01-19
        相关资源
        最近更新 更多