具有多个条件的 JS 嵌套三元

JS Nested Ternary with Multiple conditions

基本上我有以下问题:

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;

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

您已经用 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;
  }
};
    const myThing = (conditionA && conditionB) ? thingA : (conditionA) ? thingB : thingC;
       

等同于:

if(conditionA && conditionB){
   thingA
}
else if(conditionA){
   thingB
} else {
   thingC
}

尝试使用:

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

希望对您有所帮助。

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

conditionA ? thingB 

部分代码。

你真正想写的似乎是

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

但是我推荐写这篇文章,因为它更难阅读和写,正如您已经体验过的那样。我添加这个只是为了解释条件运算符的工作原理,希望 证明您不应该将它们用于任何远程复杂的事情。我发现一般情况下条件的应用非常有限,如果从未使用过,也不会错过它。 .

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

const myThing = conditionA ? (conditionB ? thingA : thingB) : thingC;
  • if conditionA is true - 评估第二个条件运算符
    • 如果 conditionBtrue - return thingA
    • 如果 conditionBfalse - return thingB
  • 如果 conditionAfalse - return 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"

对于后者,您一次只需理解一个表达式即可找出正在 return编辑的内容,而对于前者,您需要了解所有这些表达式。