【问题标题】:Ternary Operator with Logical Operators [closed]带逻辑运算符的三元运算符 [关闭]
【发布时间】:2020-04-14 02:56:55
【问题描述】:

我试图在链接时在三元运算符中使用逻辑运算符 &&,但它不起作用...例如:

(x === 5 && y === 5) ? (do something) 
: (x === 5 && y === 4) ? (do something else) 
: (x === 5 && y === 3) ? (do a third thing) 
: null

这可能吗?有没有其他方法可以做到这一点?

【问题讨论】:

标签: javascript jsx logical-operators conditional-operator


【解决方案1】:
x === 5 ? 
  y === 5 ? console.log('x=5, y=5') :
  y === 4 ? console.log('x=5, y=4') :
  y === 3 ? console.log('x=5, y=3') : null
: null

证明:

const resp = (x,y) => x === 5 ? 
                        y === 5 ? 'x==5, y==5' :
                        y === 4 ? 'x==5, y==4' :
                        y === 3 ? 'x==5, y==3' : 'x==5, y==?'
                      : 'x==?, y==?'

console.log ( '1 ,2 ', resp(1,2) )  // 1 ,2  x==?, y==?
console.log ( '5 ,2 ', resp(5,2) )  // 5 ,2  x==5, y==? 
console.log ( '5 ,4 ', resp(5,4) )  // 5 ,4  x==5, y==4

【讨论】:

  • 不错...(不错)
  • 很难维护。
【解决方案2】:

是的,你可以随心所欲:

const Question = (x,y) => (x === 5 && y === 5) ?  'x==5, y==5' 
                        : (x === 5 && y === 4) ?  'x==5, y==4' 
                        : (x === 5 && y === 3) ?  'x==5, y==3' 
                        : 'x==?, y==?' 

console.log ( '1 ,2 ', Question(1,2) )  // 1 ,2  x==?, y==?
console.log ( '5 ,2 ', Question(5,2) )  // 5 ,2  x==?, y==? 
console.log ( '5 ,4 ', Question(5,4) )  // 5 ,4  x==5, y==4

【讨论】:

    【解决方案3】:

    使用括号指定成功和失败的嵌套条件。

        (x === 5 && y === 5) ? (do something) : ((x === 5 && y === 4) ? (do something
          else) : ((x === 5 && y === 3) ? (do a third thing) : null));
    

    证明:

    const test = (x,y) => (x === 5 && y === 5) 
                          ? 'x==5, y==5' 
                          : ( (x === 5 && y === 4) 
                              ? 'x==5, y==4' 
                              : ( (x === 5 && y === 3) 
                                  ? 'x==5, y==5'
                                  : 'x==?, y==?'
                            )   );
    
    console.log ( '1 ,2 ', test(1,2) )  // 1 ,2  x==?, y==?
    console.log ( '5 ,2 ', test(5,2) )  // 5 ,2  x==?, y==? 
    console.log ( '5 ,4 ', test(5,4) )  // 5 ,4  x==5, y==4

    【讨论】:

      猜你喜欢
      • 2014-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-29
      • 1970-01-01
      相关资源
      最近更新 更多